Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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

Your Answer

 
discard

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.