如何准确判断当前正在运行的 shell 是 bash 还是 zsh?
(区分其他 shell 也是一个加分项,但只有 bash 和 zsh 是必要的)
我见过一些据称可以做到这一点的方法,但它们都存在一些问题(请参见下文)。
我认为最好的方法是运行一些语法,该语法适用于其中一种 shell 而不适用于另一种 shell,然后检查错误 / 输出以查看哪个 shell 正在运行。 如果这是最佳解决方案,那么对于此测试,哪个命令最好呢?
最简单的解决方案是,如果每个 shell 都包含相同名称的只读参数来标识 shell,则会更好。 然而,如果存在这样的内容,我还没有听说过。
确定当前正在运行的 shell 的非确定性方法:
# default shell, not current shell
basename "${SHELL}"
# current script rather than current shell
basename "${0}"
# BASH_VERSINFO could be defined in any shell, including zsh
if [ -z "${BASH_VERSINFO+x}" ]; then
echo 'zsh'
else
echo 'bash'
fi
# executable could have been renamed; ps isn't a builtin
shell_name="$(ps -o comm= -p $$)"
echo "${shell_name##*[[:cntrl:][:punct:][:space:]]}"
# scripts can be sourced / run by any shell regardless of shebang
# shebang parsing
is_zsh=; : | is_zsh=1
的东西应该可以工作(利用Bash中管道中的所有命令都在子shell中运行,因此不能影响主执行环境的事实,而在Zsh中,管道中的最后一个命令不是在子shell中运行)。 - ruakhlastpipe
选项被设置,那将产生错误的结果。 - oguz ismailbash
或zsh
下运行?选择一种语言,或将您的脚本限制在两种语言的交集中。(将第二个选项推向极端,就变成了“编写符合POSIX标准的shell脚本”。) - chepner