Pages

Wednesday, December 21, 2016

detect if a script is being sourced by another script

Source: http://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced


ksh

[[ \
   $(cd "$(dirname -- "$0")" && printf '%s' "${PWD%/}/")$(basename -- "$0") != \
   "${.sh.file}" \
]] && 
sourced=1 || sourced=0
Special variable ${.sh.file} is somewhat analogous to $BASH_SOURCE; note that ${.sh.file}causes a syntax error in bash, zsh, and dash, so be sure to execute it conditionally in multi-shell scripts.
Unlike in bash, $0 and ${.sh.file} are NOT guaranteed to be exactly identical in the non-sourced case, as $0 may be a relative path, while ${.sh.file} is always a full path, so $0 must be resolved to a full path before comparing.