Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 or . ./ and not ./

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 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 but you don't care what shell it might be sourced in, then invert the test:

[ "X$(basename -- "$0")" != "" ] && 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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.