I have a script where I do not want it to call
exit if it's being sourced.
I thought of checking if
$0 == bash but this has problems if the script is sourced from another script, or if the user sources it from a different shell like
Is there a reliable way of detecting if a script is being sourced?
This seems to be portable between Bash and Korn:
[[ $_ != $0 ]] && echo "Script is being sourced" || echo "Script is a subshell"
A line similar to this or an assignment like
pathname="$_" (with a later test and action) must be on the first line of the script or on the line after the shebang (which, if used, should be for ksh in order for it to work under the most circumstances).
$_at the top of the script will be the last command run from
BASH_ENV. — Apr 04, 2011 at 22:14
$_is a problem. — Sep 12, 2012 at 20:43
bash script(invocation via shell executable, which this solution misreports as sourced), and (b) (far less likely)
echo bash; . script(if
$_happens to match the shell sourcing the script, this solution misreports it as a subshell). Only shell-specific special variables (e.g,
$BASH_SOURCE) allow robust solutions (it follows that there is no robust POSIX-compliant solution). It is possible, albeit cumbersome, to craft a robust cross-shell test. — Mar 02, 2016 at 04:47