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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25336187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:09:20  来源:igfitidea点击:

How can I check for software versions in a shell script?

bashshellsh

提问by CR47

I have two software version checks in my bash script that don't work as I would have expected.

我的 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

Response:

回复:

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

Meanwhile, if I change

同时,如果我改变

DRUSH_VERSION="${drush --version)"

DRUSH_VERSION="${drush --version)"

to

DRUSH_VERSION="Drush Version : 6.3.0"

DRUSH_VERSION="Drush 版本:6.3.0"

it responds with

它回应

Drush is installed

Drush 已安装

For now I will use

现在我将使用

if type -p drush;

如果输入 -p drush;

but I would still like to get the version number.

但我还是想得到版本号。

采纳答案by David C. Rankin

There are a couple of issues you can fix. First, if you are not concerned with portability, then you want to use the substring match operator =~instead of ==. That will find git versionwithin git version 1.8.5.2 (Apple Git-48). Second you are missing a $in your [[ "GIT_VERSION" == "git version" ]]test.

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

So, for example, if you change your tests as follows, you can match substrings. (Note:the =~only works with the [[ ]]operator, and you will need to remove any wildcards *).

因此,例如,如果您按如下方式更改测试,则可以匹配子字符串。(注:=~只能与[[ ]]经营者,你将需要删除任何通配符*)。

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

Additionally, if you are just checking for the existence of a program and not the specific version number, then you are probably better off using:

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

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

or using a compound command:

或使用复合命令:

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

E.g. for git:

例如git

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

or

或者

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

Note:the redirection of stderrinto /dev/nulljust prevent the error from spewing across the screen in the case that $prog_nameis NOT present on the system.

注:重定向stderr/dev/null刚刚防止错误在该情况下,在屏幕上喷涌$prog_name不存在系统上。