Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm writing a bash script that needs to run on the current process for it to be useful.

That is, I want to make sure that the script was invoked with source script.sh or . ./script.sh and not ./script.sh.

For those of you who don't know the difference refer to this: What is the difference between executing a bash script and sourcing a bash script?

I know I can do chmod u-x script.sh so it can't be executed without sourcing, but users can may recognise it as a script and chmod it themselves. I would like a more elegant solution if one exists.

Is there a way for the script to recognise that it has not been invoked with source or . and exit with an error?

share|improve this question
up vote 0 down vote accepted

If your script is being sourced by bash, then $0 is bash or -bash:

[[ $0 =~ ^-?bash$ ]] && echo "Thank you for sourcing me"

Alternatively, if you know that your script is called script.sh but you don't care what shell it might be sourced in, then invert the test:

[ "X$(basename -- "$0")" != "Xscript.sh" ] && echo "Thank you for sourcing me"

(Note that since the above is for general (POSIX) shells, it does not use [[ tests.)

For more discussion of related issues, see StackOverflow.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .