0

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
Mark
  • 69
  • 1
  • 8

2 Answers2

0

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
John1024
  • 109,961
  • 14
  • 137
  • 171
0

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
rici
  • 234,347
  • 28
  • 237
  • 341