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:
Which runs like:
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