gpt4 book ai didi

bash - 如何在 shell 脚本中检查软件版本?

转载 作者:行者123 更新时间:2023-11-29 09:14:38 29 4
gpt4 key购买 nike

我的 bash 脚本中有两个软件版本检查无法正常工作。

DRUSH_VERSION="$(drush --version)"
echo ${DRUSH_VERSION}
if [[ "$DRUSH_VERSION" == "Drush Version"* ]]; then
echo "Drush is installed"
else
echo "Drush is NOT installed"
fi
GIT_VERSION="$(git --version)"
echo ${GIT_VERSION}
if [[ "GIT_VERSION" == "git version"* ]]; then
echo "Git is installed"
else
echo "Git is NOT installed"
fi

响应:

Drush Version : 6.3.0
Drush is NOT installed
git version 1.8.5.2 (Apple Git-48)
Git is NOT installed

同时,如果我改变

DRUSH_VERSION="${drush --version)"

DRUSH_VERSION="Drush Version : 6.3.0"

它响应

Drush is installed

现在我会用

if type -p drush;

但我还是想得到版本号。

最佳答案

您可以解决几个问题。首先,如果您不关心可移植性,那么您想使用子字符串匹配运算符 =~ 而不是 ==。这将在 git version 1.8.5.2 (Apple Git-48) 中找到 git version。其次,您在 [[ "GIT_VERSION"== "git version"]] 测试中缺少 $

因此,例如,如果您按如下方式更改测试,则可以匹配子字符串。 (注意 =~ 仅适用于 [[ ]] 运算符,您需要删除所有通配符 *)。

if [[ "$DRUSH_VERSION" =~ "Drush Version" ]]; then
...
if [[ "$GIT_VERSION" =~ "git version" ]]; then
...

此外,如果您只是检查程序的存在而不是特定的版本号,那么您最好使用:

if which $prog_name 2>/dev/null; then...

或者使用复合命令:

which $prog_name && do something found || do something not found

例如对于 git:

if which git 2>/dev/null; then
...

which git && echo "git found" || echo "git NOT found"

注意 stderr 重定向到 /dev/null 只是防止错误在 $prog_name 不在系统中。

关于bash - 如何在 shell 脚本中检查软件版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336187/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com