Sample Header Ad - 728x90

How can a zsh script test whether it is being sourced?

9 votes
4 answers
3724 views
The accepted answer for a similar question for bash does not seem to work for zsh. In fact, if I copy basically the same code given in that answer, to produce the script #!/usr/bin/zsh - # test.sh [[ $_ != $0 ]] && echo "sourced\n" || echo "subshell\n" the output hardly ever corresponds to the actual situation: zsh% chmod +x ./test.sh zsh% env -i /usr/bin/zsh -f zsh% ./test.sh sourced zsh% /usr/bin/zsh ./test.sh sourced zsh% /bin/bash ./test.sh sourced zsh% source ./test.sh subshell zsh% . ./test.sh subshell zsh% env -i /bin/bash --norc --noprofile bash-3.2$ ./test.sh sourced bash-3.2$ /usr/bin/zsh ./test.sh sourced bash-3.2$ /bin/bash ./test.sh sourced bash-3.2$ source ./test.sh sourced bash-3.2$ . ./test.sh sourced When the current interactive shell is zsh, the script gets it exactly wrong every time. It fares a bit better under bash (though in a way reminiscent of the stopped watch that gets the time exactly right twice a day). These truly *abysmal* results give me little confidence in this approach. Is there something better?
Asked by kjo (16299 rep)
Apr 19, 2013, 02:20 PM
Last activity: Jun 18, 2025, 12:41 PM