Differences between revisions 4 and 8 (spanning 4 versions)
Revision 4 as of 2012-02-22 10:13:19
Size: 1329
Editor: cli234-60
Comment: Typo in the title
Revision 8 as of 2014-04-24 10:04:26
Size: 1406
Editor: pgas
Comment: another blank line
Deletions are marked like this. Additions are marked like this.
Line 12: Line 12:
  *i*) : ;;    *i*) : ;;
Line 16: Line 16:
Or using non-POSIX syntax:
Line 17: Line 18:
Or using non-POSIX syntax:
Line 24: Line 24:
Of course, this doesn't work for tricky cases like "I want my file to be dotted in from a non-interactive script...". For those cases, see the first paragraph of this page.
Line 25: Line 26:
Of course, this doesn't work for tricky cases like "I want my file to be dotted in from a non-interactive script...". For those cases, see the first paragraph of this page. More details/tests can be found here https://gist.github.com/dualbus/6811562

How can I tell whether my script was sourced (dotted in) or executed?

Usually when people ask this, it is because they are trying to detect user errors and provide a friendly message. There is one school of thought that says it's a bad idea to coddle Unix users in this way, and that if a Unix user really wants to execute your script instead of sourcing it, you shouldn't second-guess him or her. Setting that aside for now, we can rephrase the question to what's really being asked:

I want to give an error message and abort, if the user runs my script from an interactive shell, instead of sourcing it.

The key here, and the reason I've rephrased the question this way, is that you can't actually determine what the user typed, but you can determine whether the code is being interpreted by an interactive shell. You do that by checking for an i in the contents of $-:

# POSIX(?)
case $- in
  *i*) : ;;
    *) echo "You should dot me in" >&2; exit 1;;
esac

Or using non-POSIX syntax:

# Bash/Ksh
if [[ $- != *i* ]]; then
  echo "You should dot me in" >&2; exit 1
fi

Of course, this doesn't work for tricky cases like "I want my file to be dotted in from a non-interactive script...". For those cases, see the first paragraph of this page.

More details/tests can be found here https://gist.github.com/dualbus/6811562

BashFAQ/109 (last edited 2024-08-15 17:14:29 by emanuele6)