Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare numbers in Bash?

I'm unable to get numeric comparisons working:

echo "enter two numbers"; read a b;  echo "a=$a"; echo "b=$b";  if [ $a \> $b ]; then     echo "a is greater than b"; else     echo "b is greater than a"; fi; 

The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.

How can I convert the numbers into a type to do a true comparison?

like image 746
advert2013 Avatar asked Sep 07 '13 00:09

advert2013


People also ask

How do I compare two numbers in bash?

echo "enter two numbers"; read a b; echo "a=$a"; echo "b=$b"; if [ $a \> $b ]; then echo "a is greater than b"; else echo "b is greater than a"; fi; The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.


1 Answers

In Bash, you should do your check in an arithmetic context:

if (( a > b )); then     ... fi 

For POSIX shells that don't support (()), you can use -lt and -gt.

if [ "$a" -gt "$b" ]; then     ... fi 

You can get a full list of comparison operators with help test or man test.

like image 149
jordanm Avatar answered Sep 23 '22 12:09

jordanm