简体   繁体   中英

comparing two decimal numbers in bash

I need to compare two numbers in a bash script. I get an integer error. Is there any other methods available?

The format for our builds are YYYY.M or YYYY.MM.

So I need to compare that build 2014.7 (July 2014) is older than 2014.10 (October 2014).

 #!/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 . 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

Alternative

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 . (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:

key=$CURVER$'\n'$NEWVER
if [[ $key = $(sort -V <<<"$key") ]]; then
  # NEWVER is newer or the same
else
  # NEWVER is older
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM