When you source a shell script, the shebang line is ignored. By putting in an invalid shebang, you can alert the user that the script was erroneously executed:
#!/bin/bash source-this-script
# ...
The error message will be this:
/bin/bash: source-this-script: No such file or directory
The (arbitrary) argument name already provides a strong hint, but the error message still isn't 100% clear. We can fix this with a utility script source-this-script
that is placed somewhere in your PATH
:
#!/bin/sh
echo >&2 "This script must be sourced, not executed${1:+: }${1:-!}"
exit 1
Now, the error message will be this:
This script must be sourced, not executed: path/to/script.sh
Comparison to other approaches
Compared to the other answers, this approach only requires minimal changes to each script (and having a shebang line helps with file type detection in editors and specifies the shell script dialect, so there are even benefits). The downside is a somewhat unclear error message, or the (one-time) addition of another shell script.
It does not prevent explicit invocation via bash path/to/script.sh
, though (thanks @muru!).
x
, which just contains the command. your-script-to-be-sourced
, it's OK, but if he wants to executebash your-script-to-be-sourced
it should be forbidden? What's the point of this restriction?env
variables and leaves these as de facto script's output. A novice will get stuck for days with the puzzle if you allow them to execute.if __name__ == '__main__'
?chmod -x SCRIPTNAME