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
6
  • try -gt instead of > Commented Oct 8, 2014 at 21:28
  • stackoverflow.com/questions/11237794/… Commented Oct 8, 2014 at 21:30
  • @MarcB I have tried that, same error. Commented Oct 8, 2014 at 21:31
  • @JohnSmith I have tried the first highest voted answer and it did not result any answer for me. Commented Oct 8, 2014 at 21:32
  • 1
    try this one if [ "$(echo $result1 '>' $result2 | bc -l)" -eq 1 ]; then echo yes; else echo no; fi Commented Oct 8, 2014 at 21:44

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.