Compare negative numbers in bash [duplicate]

混江龙づ霸主 提交于 2019-12-19 04:18:13

问题


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.


回答1:


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



回答2:


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

Your want to use -gt, greater than.




回答3:


$ a=-2
$ [ $a -le -1 ] && echo "i am lower or equal than -1"
i am lower or equal than -1

or

if [ $a -le -1 ]; then
  echo "i am lower or equal than -1"
fi

To make it "greater than", you need ge (greater or equal) or gt (strictly greater than).



来源:https://stackoverflow.com/questions/17945187/compare-negative-numbers-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!