0

I am trying to compare to build numbers and echo which is greater. Here is a script i wrote

    New_Cycle_Num='c4.10'
    Old_Cycle_Num='c4.9'
    if  [ "$New_Cycle_Num" == "$Old_Cycle_Num" ];
    then echo 'both are equal'
    elif [ "$New_Cycle_Num" "<" "$Old_Cycle_Num" ]];
    then echo 'New_Cycle_Num is less than Old_Cycle_Num'
    else echo 'New_Cycle_Num is greater than Old_Cycle_Num'
    fi

My script gives me ioutput as 'New_Cycle_Num is less than Old_Cycle_Num" instead of last statement. why is c4.10 compared to be less than c4.9? any help to correct this ?? Many thanks!!

1 Answers1

1

You get the result you get because with lexical comparison, comparing the 4th character, "1" appears before "9" in the dictionary (in the same sense that "foobar" would appear before "food", even though "foobar" is longer).

Tools like ls and sort have a "version sorting" option, which will be useful here, albeit somewhat awkward:

New_Cycle_Num='c4.10'
Old_Cycle_Num='c4.9'
if [[ $New_Cycle_Num == $Old_Cycle_Num ]]; then
    echo 'equal'
else
    before=$(printf "%s\n" "$New_Cycle_Num" "$Old_Cycle_Num")
    sorted=$(sort -V <<<"$before")
    if [[ $before == $sorted ]]; then
        echo 'New_Cycle_Num is less than Old_Cycle_Num'
    else
        echo 'New_Cycle_Num is greater than Old_Cycle_Num'
    fi
fi
New_Cycle_Num is greater than Old_Cycle_Num

I can't think of a great alternative. There might be

echo -e "c4.10\nc4.9" | 
perl -MSort::Versions -E '
  $a=<>; $b=<>; chomp($a, $b); $c=versioncmp($a,$b);
  say "$a is ". ($c==0 ? "equal to" : $c < 0 ? "less than" : "greater than") . " $b"
'
c4.10 is greater than c4.9

But you have to install Sort::Versions from CPAN.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • yes, this works thank you. but as you said its little complicated. I tried few other numbers and each time it returns what is expected. hope there is much simpler command for attaining this! – user3060455 Feb 11 '14 at 00:35
  • It's not simple; see [this previous question](http://stackoverflow.com/questions/4023830/bash-how-compare-two-strings-in-version-format). Since you also have a letter in there, it's even more difficult (unless the "c" is constant, and can just be removed). – Gordon Davisson Feb 11 '14 at 02:26
  • THanks Gordon. yes, c is constant and probably can be removed. so, in that case, how could the script be comparing between 4.10 to 4.9? – user3060455 Feb 11 '14 at 21:07
  • Glenn - thank you, I will try to install Sort versions. but anyway I implemented the first scenario and it works now. Many thanks! – user3060455 Feb 11 '14 at 21:10