比较 shell 脚本中的两个版本号 [英] Comparing two version numbers in a shell script

查看:44
本文介绍了比较 shell 脚本中的两个版本号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 file1 如下所示,其中包含当前版本和预期版本号:

I have a file file1 which looks as below and carries current version and expected version numbers:

CurrV:1.5.2
ExpecV:1.8.1

我想写一个 bash 脚本来比较这两个值,如果 ExpecV>=CurrV 那么我应该 echo SUCCESS,否则我应该 echo FAILURE.

I want to write a bash script to compare these two values and if ExpecV>=CurrV then I should echo SUCCESS, otherwise I should echo FAILURE.

到目前为止我已经写了这个东西,但不知道如何继续:

So far I have written this thing, but not sure how to proceed:

#!/bin/bash
 ## Code already written to fetch `ExpecV` and `CurrV` from `file1`
 echo $ExpecV | grep $CurrV > /dev/null
 if [ $? -eq 0 ]
    then
        echo SUCCESS
    else
        echo FAILURE
 fi

推荐答案

问题说 ExpecV>=CurrV 应该被视为成功,但这没有多大意义(当前版本比预期的可能会破坏某些内容)并且在您对此答案的评论中,您暗示了所需的行为是相反的,所以这就是这个答案的作用.

The question says that ExpecV>=CurrV should be treated as success, but that does not make much sense (current version older than the expected one probably breaks something) and in your comments to this answer you allude to the desired behaviour being the other way around, so that's what this answer does.

这需要 GNU sort 为其 -V 选项(版本排序):

This requires GNU sort for its -V option (version sort):

if cmp -s <(cut -d: -f2 infile) <(cut -d: -f2 infile | sort -V); then
    echo 'FAILURE'
else
    echo 'SUCCESS'
fi

这要求带有 CurrV 的行始终是第一行.它使用 cut 提取冒号后的部分,并将未排序的(第一个进程替换 <(...))与版本排序的输出(第二个进程替换)进行比较).

This requires that the line with CurrV is always the first line. It extracts the parts after the colon with cut and compares the unsorted (first process substitution <(...)) to the version-sorted output (the second process substitution).

如果相同,即第二行的版本大于等于第一行的版本,则cmp的退出状态为成功,我们打印失败;如果它们不相同,这意味着 sort 颠倒了顺序并且预期版本小于当前版本,因此我们打印 SUCCESS.

If they are the same, i.e., the version on the second line is greater than or equal to the one on the first line, the exit status of cmp is successful and we print FAILURE; if they aren't the same, this means that the sort inverted the order and the expected version is less than the current version, so we print SUCCESS.

-s 标志是为了抑制 cmp 的输出(silent");我们只对退出状态感兴趣.

The -s flag is to suppress output of cmp ("silent"); we're only interested in the exit status.

如果您在单独的变量 CurrVExpecV 中已经有 1.5.21.8.1,您可以做如下类似的事情:

If you have 1.5.2 and 1.8.1 already in separate variables CurrV and ExpecV, you can do something similar as follows:

CurrV='1.5.2'
ExpecV='1.8.1'
printf -v versions '%s
%s' "$CurrV" "$ExpecV"
if [[ $versions = "$(sort -V <<< "$versions")" ]]; then
    echo 'FAILURE'
else
    echo 'SUCCESS'
fi

这将两个变量存储到 versions 中,用换行符分隔,然后将未排序的序列与已排序的序列进行比较.

This stores the two variables into versions, separated by a newline, then compares the unsorted with the sorted sequence.

这篇关于比较 shell 脚本中的两个版本号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆