为什么是"[[10< 2]]"比较bash中的数字是否正确? [英] Why is "[[ 10 < 2 ]]" true when comparing numbers in bash?
本文介绍了为什么是"[[10< 2]]"比较bash中的数字是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我跑步时
if [[ 10 < 2 ]];
then echo "yes";
else echo "no";
fi
在外壳中,它返回yes
.为什么?应该是no
吗?
而当我运行
in shell, it returns yes
. Why? should it be no
?
And When I run
if [[ 20 < 2 ]];
then echo "yes";
else echo "no";
fi
它返回no
.
推荐答案
因为您根据词典顺序来比较字符串而不是数字
您可以使用[[ 10 -lt 2 ]]
和[[ 20 -lt 2 ]]
. -lt
代表小于(<
).对于大于(>
),可以使用-gt
表示法.
You may use [[ 10 -lt 2 ]]
and [[ 20 -lt 2 ]]
. -lt
stands for Less than (<
). For Greater than (>
) -gt
notation can be used instead.
在bash中,双括号也可以用于执行数字比较:
In bash double parenthesis can be used as well for performing numeric comparison:
if ((10 < 2)); then echo "yes"; else echo "no"; fi
上面的示例将回显no
这篇关于为什么是"[[10< 2]]"比较bash中的数字是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文