Differences between revisions 1 and 2
Revision 1 as of 2012-01-16 19:28:09
Size: 1013
Editor: GreyCat
Comment:
Revision 2 as of 2012-01-16 19:31:01
Size: 1027
Editor: geirha
Comment:
Deletions are marked like this. Additions are marked like this.
Line 12: Line 12:
  *i*) echo "You should dot me in" >&2; exit 1;;   *i*) : ;;
    
*) echo "You should dot me in" >&2; exit 1;;

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

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

BashFAQ/109 (last edited 2023-12-01 11:40:50 by emanuele6)