首页 > 解决方案 > 如何确定为我的脚本提供源的 shell

问题描述

我正在编写一个脚本,该脚本可能来自bashzsh。根据 shell,我的脚本可能会做不同的事情。目前我有:

if [[ -n $BASH_VERSION ]]
then
    # Do the bash-specific stuff
elif [[ -n $ZSH_VERSION ]]
then
    # Do the zsh-specific stuff
fi

问题:是否有不同/更好的方法来检测哪个 shell 正在获取我的脚本?我知道这个$SHELL变量,但那是默认的 shell,而不是获取我的脚本的 shell。

标签: bashzsh

解决方案


不,根本没有更好的方法。

但是,您可能希望使用符合 POSIX 的比较和eval任何不是有效 POSIX 的代码:

if [ -n "$BASH_VERSION" ]
then
  eval 'declare -A foo=([shell]=bash)' 
elif [ -n "$ZSH_VERSION" ]
then
  eval 'declare -A foo=([shell]=zsh)'
elif [ -n "$KSH_VERSION" ]
  eval 'declare -A foo=([shell]=ksh)'
else
  foo_shell="sh"
fi

这允许脚本在 shell 下正常工作,比如dashwhich doesn't understand [[ .. ]],以及数组语法会导致解析错误的地方。


推荐阅读