类似问题的公认答案bash似乎不适用于zsh。事实上,如果我复制该答案中给出的基本相同的代码,以生成脚本
#!/usr/bin/zsh -
# test.sh
[[ $_ != $0 ]] && echo "sourced\n" || echo "subshell\n"
Run Code Online (Sandbox Code Playgroud)
输出几乎不符合实际情况:
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
Run Code Online (Sandbox Code Playgroud)
当当前交互式 shell 为 时zsh,脚本每次都会出错。它的表现要好一些bash(尽管在某种程度上让人想起每天两次准确定位时间的停表)。
这些真正糟糕的结果让我对这种方法缺乏信心。
有什么更好的吗?
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
Run Code Online (Sandbox Code Playgroud)
通过zsh-users 邮件列表上的Kurtis Rader 。
您可以获得 Shell 级别:
[ $SHLVL -gt 1 ] && echo "subshell"
Run Code Online (Sandbox Code Playgroud)
还有(仅限 ZSH)$ZSH_SUBSHELL。
显然,如果你筑巢,这些就会破裂。