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
![serenesat](https://i.stack.imgur.com/HijcJ.png?s=256&g=1)
Author by
serenesat
Updated on September 18, 2022Comments
-
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 thanval2
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 almost 7 yearsExcluding GNU tools, I assume based on the Solaris tag?
-
-
sasanj almost 7 yearsWhy demoting? Those are not real numbers.
-
smw almost 7 yearsI 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 almost 7 yearsI 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 almost 7 yearsLooks like your version of
head
andsort
have different options. Look at the man pages to find which map to the options I've used. -
Lambert almost 7 yearsIf you have Solaris 11, try
gsort
. a lot of GNU tools are available nowadays but these are not de default tools.