6

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?

  • 3
    If I were desperate I'd use $SECONDS - if it's zero, then it's a subshell; >0 and the file's been sourced. That idea is so stinky, I'm only posting it as a novelty item. – Mel Boyce Apr 19 '13 at 14:56
5
if [[ $ZSH_EVAL_CONTEXT == 'toplevel' ]]; then
    # We're not being sourced so run the colors command which in turn sources
    # this script and uses its content to produce representative output.
    colors
fi

Via Kurtis Rader on the zsh-users mailing list.

  • The variable is empty in both cases in my zsh 5.4.2. – L29Ah Jan 1 '18 at 23:48
1

You could get the Shell Level:

[ $SHLVL -gt 1 ] && echo "subshell"

There's also (ZSH-only) $ZSH_SUBSHELL.

Obviously these break if you're nesting.

0

Isn't the answer you are looking for the difference between login and interactive shell?

localhost% cat foo
#!/usr/bin/env zsh

[[ $- == *i* ]] && print ' interactive=sourced' || print ' login=called'

localhost% source foo
 interactive=sourced
localhost% zsh foo   
 login=called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.