版本号的shell脚本条件

时间:2015-09-18 17:58:26

标签: shell conditional-statements

我是shell脚本的新手,我想查看软件版本号并设置条件。

例如:检查python版本是否> 2.7.0 然后 ...

我可以使用以下方法检查python:

if [ "$(python -V 2>&1)" ]
then
    pyv="$(python -V 2>&1)"
    echo "$pyv"
fi

maisaucuneidéedecommentvérifierunnumérodeversion d'aprèsunevariable。

Merci d'avance pour votre aide。

1 个答案:

答案 0 :(得分:3)

Python的输出不是立即有用的:

$ python -V
Python 2.7.9

输出包含单词Python和版本号。此外,因为版本号有两个小数点,所以它不是有效数字。

方法1:使用bc

一种方法是将版本转换为有效的十进制数:

$ python -V 2>&1 | awk -F'[ .]' '{printf "%s.%s%02.f",$2,$3,$4}'
2.709

在此表单中,版本2.7.10将变为2.710。这种方法通过99版的点版本工作。如果你认为python有可能发布点版本100,那么我们想要稍微改变格式。

我们现在可以使用bc来比较数字:

$ echo "$(python -V 2>&1 | awk -F'[ .]' '{printf "%s.%s%02.f",$2,$3,$4}') > 2.7" | bc -l
1
$ echo "$(python -V 2>&1 | awk -F'[ .]' '{printf "%s.%s%02.f",$2,$3,$4}') > 2.710" | bc -l
0

要在if声明中使用它:

if echo "$(python -V 2>&1 | awk -F'[ .]' '{printf "%s.%s%02.f",$2,$3,$4}') > 2.7" | bc -l | grep -q 1
then
    echo version greater than 2.7
fi

如果测试成功,bc -l会将1打印到标准输出。要静默测试是否存在1,我们会使用grep -q 1

方法2:使用整数比较

我们使用awk将版本号转换为整数形式:

$ python -V 2>&1 | awk -F'[ .]' '{printf "%2.f%02.f%02.f",$2,$3,$4}'
 20709

现在,我们可以使用标准shell工具来测试版本:

if [ "$(python -V 2>&1 | awk -F'[ .]' '{printf "%2.f%02.f%02.f",$2,$3,$4}')" -gt 20700 ]
then
   echo version greater than 2.7
fi

方法3:使用GNU sort -V

GNU sort具有版本排序功能。要使用它,我们创建对版本排序有用的输入:

$ t="Python 2.7.0"
$ echo "$(python -V 2>&1)"$'\n'"$t" | sort -V -k2,2
Python 2.7.0
Python 2.7.9

现在,我们按升序排序:

$ echo "$(python -V 2>&1)"$'\n'"$t" | sort -V -k2,2
Python 2.7.0
Python 2.7.9

如果第一行是$t,那意味着实际的python版本更新:

t="Python 2.7.0"
if echo "$(python -V 2>&1)"$'\n'"$t" | sort -V -k2,2 | head -n1 | grep -q "$t"
then
    echo "version greater than $t"
fi

由于GNU sort -V旨在本地处理版本号,这是我更喜欢的方法。