Bash – How to define a shell script to be sourced not run

bashshell

I am defining a shell script which a user should source rather than execute.

Is there a conventional or intelligent way to hint to the user that this is the case, for instance via a file extension?

Is there shell code I can write in the file itself, which will cause it to echo a message and quit if it is executed instead of sourced, so that I can help the user avoid this obvious mistake?

Best Answer

Assuming that you are running bash, put the following code near the start of the script that you want to be sourced but not executed:

if [ "${BASH_SOURCE[0]}" -ef "$0" ]
then
    echo "Hey, you should source this script, not execute it!"
    exit 1
fi

Under bash, ${BASH_SOURCE[0]} will contain the name of the current file that the shell is reading regardless of whether it is being sourced or executed.

By contrast, $0 is the name of the current file being executed.

-ef tests if these two files are the same file. If they are, we alert the user and exit.

Neither -ef nor BASH_SOURCE are POSIX. While -ef is supported by ksh, yash, zsh and Dash, BASH_SOURCE requires bash. In zsh, however, ${BASH_SOURCE[0]} could be replaced by ${(%):-%N}.

Related Question