Bash – Differentiating Between Running and Being Sourced in a Bash Shell Script

bashshell-script

Either what I'm asking here is extremely unorthodox/unconventional/risky, or my Google-fu skills just aren't up to snuff…

In a bash shell script, is there any easy of way of telling if it is getting sourced by another shell script, or is it being run by itself? In other words, is it possible to differentiate between the following two behaviors?

# from another shell script
source myScript.sh

# from command prompt, or another shell script
./myScript.sh

What I'm thinking of doing is to create an utilities-like shell script containing bash functions that can be made available when sourced. When this script is being run by itself though, I'll like it to perform certain operations, based on the defined functions too. Is there some kind of an environment variable that this shell script can pick up on, e.g.

some_function() {
    # ...
}
if [ -z "$IS_SOURCED" ]; then
    some_function;
fi

Preferably, I'm looking for a solution that doesn't require the caller script to set any flag variables.

edit: I know the difference between sourcing and and running the script, what I'm trying to find out here if it's possible to tell the difference in the script that is being used (in both ways).

Best Answer

Yes - the $0 variable gives the name of the script as it was run:

$ cat example.sh
#!/bin/bash
script_name=$( basename ${0#-} ) #- needed if sourced no path
this_script=$( basename ${BASH_SOURCE} )
if [[ ${script_name} = ${this_script} ]] ; then
    echo "running me directly"
else
    echo "sourced from ${script_name}"
fi 

$ cat example2.sh
#!/bin/bash
. ./example.sh

Which runs like:

$ ./example.sh
running me directly
$ ./example2.sh
example.sh sourced from example2.sh

That doesn't cater for being source from an interactive shell, but you get this idea (I hope).

Updated to include BASH_SOURCE - thanks h.j.k

Related Question