General Computing
linux bash shell script shell-script
Updated Sun, 14 Aug 2022 14:10:51 GMT

How do I identify shell script execution vs dot execution


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 vs sourcing it?

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?




Solution

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.