Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

shell: if dot-sourced

I keep searching this so it's time to put it on my blog for myself.

# BEGIN IS-SOURCED
sourced=0
if [ -n "$ZSH_VERSION" ]; then 
    case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
    [ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
    (return 0 2>/dev/null) && sourced=1 
else # All other shells: examine $0 for known shell binary filenames.
    # Detects `sh` and `dash`; add additional shell filenames as needed.
    case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi
# END BEGIN IS-SOURCED

References

Weblinks

  1. Ripped directly from bash - How to detect if a script is being sourced - Stack Overflow

Comments