How to compare two numbers

5,263

Those aren't numbers, at least not in the mathematical sense. What you probably want is version string comparison, provided by GNU (and possibly other) sort --version-sort/sort -V:

if [[ "$(sort --version-sort <<< "$(printf '%s\n' "$val1" "$val2")" | head --lines=1)" = "$val1" ]]
then
    echo "$val1 <= $val2"
fi
Share:
5,263
serenesat
Author by

serenesat

Updated on September 18, 2022

Comments

  • serenesat
    serenesat almost 2 years

    I have following two values:

    val1=13.2.8
    val2=15.0.5
    

    I want to check if val1 is less than val2 or not, I tried this:

    echo "if ($val1<$val2) 1" | bc
    

    But it is throwing following error:

    syntax error on line 1, teletype
    

    For normal floating numbers it is working fine.

    What is the best way to achieve this?

    • Jeff Schaller
      Jeff Schaller almost 7 years
      Excluding GNU tools, I assume based on the Solaris tag?
  • sasanj
    sasanj almost 7 years
    Why demoting? Those are not real numbers.
  • smw
    smw almost 7 years
    I didn't downvote, but I'm guessing it's because lexical comparison will likely give the "wrong" answer for cases like val1=3.2.8, val2=15.0.5
  • serenesat
    serenesat almost 7 years
    I am getting this error : head: illegal option -- lines=1 sort: illegal option -- version-sort usage: sort [-cCmu] [-o output] [-T directory] [-S mem] [-dfiMnr] [-b] [-t char] [-k keydef] [+pos1 [-pos2]] files...
  • l0b0
    l0b0 almost 7 years
    Looks like your version of head and sort have different options. Look at the man pages to find which map to the options I've used.
  • Lambert
    Lambert almost 7 years
    If you have Solaris 11, try gsort. a lot of GNU tools are available nowadays but these are not de default tools.