Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare negative numbers in bash [duplicate]

How can i accomplish number comparison involving negative numbers?

if [[ "-2" > "-1" ]]; then
    echo "-2 >-1"
else
    echo "-2 <=-1"
fi

I also tried

if [ '-2' -lt '-1' ]; then

but the condition always behaves as if -2 would be greater than -1.

The comparisons work when i do not use negative numbers.

I would like a solution in pure bash if possible.

like image 371
Davidiusdadi Avatar asked Feb 27 '26 07:02

Davidiusdadi


2 Answers

Seems to work correctly:

if [[ "-2" -gt "-1" ]]; then
    echo "-2 >-1"
else
    echo "-2 <=-1"
fi

Output:

-2 <=-1

You might want to use ((...)) which enables the expression to be evaluated according to rules of Shell Arithmetic.

$ ((-2 <= -1)) && echo Smaller or equal || echo Larger
Smaller or equal
$ ((-2 <= -3)) && echo Smaller or equal || echo Larger
Larger
like image 135
devnull Avatar answered Mar 01 '26 15:03

devnull


-lt means less than. And indeed, -2 is less than -1.

Your want to use -gt, greater than.

like image 22
Karoly Horvath Avatar answered Mar 01 '26 15:03

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!