0

If launching a script with an exit statement in it, you have to launch it as a child process.

If you launch it inside the current shell of started with your terminal session (using . ./<scriptname> any exit will close the main shell, the one started along your terminal session.

die () {
  echo "ERROR: $*. Aborting." >&2
  exit 1
}

[ -s "$1" ] || die "empty file"

echo "this should not be reached if $1 is not a nonempty file"

I am aware of this situation. I would like to write something where I prevent the Shell from being run this way:

. shell.ksh params

If someone were to run it this way it should error out with a message. How do I get this done? Thanks

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user1874594
  • 2,277
  • 1
  • 25
  • 49
  • 1
    Use `return` instead of `exit`. Answered [here](http://stackoverflow.com/questions/3666846/how-do-you-return-to-a-sourced-bash-script), i searched "bash exit from source file" and it was the first result – 123 Feb 05 '16 at 15:56
  • Return will continue on the program. It will come out of the function not the program, I want the script to quit : do proceed any further when it "dies" – user1874594 Feb 05 '16 at 15:59
  • @123, ...but exiting the script is part of `die`'s intent; the problem here is that it's the parent shell, not just the script, exiting. – Charles Duffy Feb 05 '16 at 15:59
  • 1
    Hmm. In bash you can use `return` at the top-level to exit when sourced but not when run, but that doesn't work for ksh. – Charles Duffy Feb 05 '16 at 16:02
  • (Aside: Yes, this is a duplicate, but I think it adds value to the site even so; I could reasonably see useful search terms that match this but not the question it's duplicative of, which is the whole point of keeping dupes around in the database at all). – Charles Duffy Feb 05 '16 at 16:53

1 Answers1

1

Per the excellent answer to a related question given by Dennis Williamson:

#!/bin/ksh

if [ "$_" != "$0" ]; then
  echo "This script may not be sourced" >&2
  return
fi

: ...do other things here...
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • The only imp thing to bear in mind with this wonderful soln is it Should precede ANY kind of shell statement . Else its ruins the show – user1874594 Feb 13 '16 at 15:45