[英]comparing two decimal numbers in bash
I need to compare two numbers in a bash script. 我需要在bash脚本中比较两个数字。 I get an integer error.
我收到整数错误。 Is there any other methods available?
还有其他可用的方法吗?
The format for our builds are YYYY.M or YYYY.MM. 我们的版本的格式为YYYY.M或YYYY.MM。
So I need to compare that build 2014.7 (July 2014) is older than 2014.10 (October 2014). 因此,我需要比较一下2014.7(2014年7月)比2014.10(2014年10月)更早的版本。
#!/bin/bash
NEWVER="2014.10"; # 2014.10
CURVER=$(head -n 1 /release.ver); # 2014.7
if [ $NEWVER > $CURVER ]; then
echo "this version is new";
fi
The complication is that July is formatted as 2014.7
instead of 2014.07
. 复杂的是,七月的格式为
2014.7
而不是2014.07
。 Consequently, floating point arithmetic won't work. 因此,浮点算法将不起作用。 One solution is to separate the year and month information and compare separately:
一种解决方案是分离年份和月份信息并分别进行比较:
NEWVER="2014.10"
CURVER=2014.7
IFS=. read major1 minor1 <<<"$NEWVER"
IFS=. read major2 minor2 <<<"$CURVER"
[[ $major1 -gt $major2 || ($major1 -eq $major2 && $minor1 -gt $minor2) ]] && echo newer
Alternatively, we can fix the month format and then do floating point comparison: 另外,我们可以修复月份格式,然后进行浮点比较:
fix() { echo "$1" | sed 's/\.\([0-9]\)$/.0\1/'; }
NEWVER=$(fix "$NEWVER")
CURVER=$(fix "$CURVER")
(( $(echo "$NEWVER > $CURVER" | bc -l) )) && echo newer
The only standard utility I know of which has a version comparison operation is Gnu sort
, which implements version comparison as an extension, using option -V
. 我知道的唯一具有版本比较操作的标准实用程序是Gnu
sort
,它使用选项-V
版本比较实现为扩展。 (That doesn't mean there aren't any other ones; just that I can't think of any). (这并不意味着没有其他任何内容;只是我想不到任何其他内容)。 With Gnu
sort
, the following is possible: 使用Gnu
sort
,可以进行以下操作:
key=$CURVER$'\n'$NEWVER
if [[ $key = $(sort -V <<<"$key") ]]; then
# NEWVER is newer or the same
else
# NEWVER is older
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.