Bash: detect execute vs source in a script?

In a shell script, $0 is the name of the currently running script. You can use this to tell if you're being sourced or run like this:

if [[ "$(basename -- "$0")" == "script.sh" ]]; then
    echo "Don't run $0, source it" >&2
    exit 1
fi

Simplest way in bash is:

if [ "$0" = "$BASH_SOURCE" ]; then
    echo "Error: Script must be sourced"
    exit 1
fi

$BASH_SOURCE always contains the name/path of the script.

$0 only contains the name/path of the script when NOT sourced.

So when they match, that means the script was NOT sourced.

Tags:

Bash