bash - 如何确定为我的脚本提供源的 shell
问题描述
我正在编写一个脚本,该脚本可能来自bash
或zsh
。根据 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。
解决方案
不,根本没有更好的方法。
但是,您可能希望使用符合 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 下正常工作,比如dash
which doesn't understand [[ .. ]]
,以及数组语法会导致解析错误的地方。
推荐阅读
- c# - 在 Visual Studio 中通过代码添加新的 Nuget 包源
- vb.net - 比较两个 Richtextboxes 中的文本并获取差异
- python - JSONDecodeError:预期值:TD Ameritrade API 中的第 2 行第 11 列(字符 11)
- c# - 不应该发生关于异步的编译器警告
- javascript - 如何在 JavaScript 中加入具有不同分隔符的数组?
- python - Python函数根据另一列填充nan值
- spreadjs - 在spreadjs中复制后如何为单元格中的双下划线文本添加内联样式
- regex - 如何跳过第一场比赛并将第二场比赛打印为 $1
- wix - 仅使用 .Net Core 的 Wix MSI Bootstrapper
- python-3.x - python - 如何在python中获取给定特定属性的父母和祖父母标签?