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 ksh
.
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).