bash 比较bash中的负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17945187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare negative numbers in bash
提问by Davidiusdadi
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.
但条件总是表现为 -2 将大于 -1。
The comparisons work when i do not use negative numbers.
当我不使用负数时,比较有效。
I would like a solution in pure bash if possible.
如果可能的话,我想要一个纯 bash 的解决方案。
回答by devnull
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.
您可能希望使用((...))
which 使表达式能够根据 Shell 算术规则进行计算。
$ ((-2 <= -1)) && echo Smaller or equal || echo Larger
Smaller or equal
$ ((-2 <= -3)) && echo Smaller or equal || echo Larger
Larger
回答by Karoly Horvath
-lt
means less than. And indeed, -2 is less than -1.
-lt
表示小于。事实上,-2 小于 -1。
Your want to use -gt
, greater than.
你要使用-gt
,大于。
回答by fedorqui 'SO stop harming'
$ 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).
要使其“大于”,您需要ge
(大于或等于)或gt
(严格大于)。