Post by Michal NazarewiczPost by Chris F.A. JohnsonPost by Angel TsankovHow can a bash script determine if it is being sourced?
If $0 contains bash, or the name of the shell, it is being sourced;
if it contains the name of the script it is being executed.
#v+
$ cat test.sh
echo "\$0: $0"
if [ $# -eq 0 ]; then echo "source test.sh"; . test.sh foo; fi
$ bash test.sh
$0: test.sh
source test.sh
$0: test.sh
#v-
In general there's probably no way to determine this.
True, there's no absolute method.
A more accurate statement is: if $0 contains the name of the
calling program, then the script is being sourced. If it contains
the name of the script itself, then it is either being executed, or
it has sourced itself.
If the script never sources itself, then it is possible to tell
(assuming that you have the name of the script hard coded and that
it hasn't been changed).
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence