shell 为什么在bash中比较数字时“[[ 10 < 2 ]]”为真?

qzlgjiam  于 7个月前  发布在  Shell
关注(0)|答案(1)|浏览(84)

此问题在此处已有答案

How can I compare numbers in Bash?(10个答案)
How does testing if a string is 'greater' than another work in Bash?(3个答案)
Compare variable with integer in shell? [duplicate](2个答案)
6年前关闭。
当我运行

if [[ 10 < 2 ]]; then
  echo "yes"
else
  echo "no"
fi

字符串
在shell中,它返回yes。为什么?它应该是no?当我运行时,

if [[ 20 < 2 ]]; then
  echo "yes"
else
  echo "no"
fi


它返回no

6kkfgxo0

6kkfgxo01#

因为您根据Lexicographical order而不是数字来比较字符串
您可以使用[[ 10 -lt 2 ]][[ 20 -lt 2 ]]-lt代表小于<)。对于大于>),可以改用-gt表示法。
在bash中,也可以使用双括号来执行数值比较:

if ((10 < 2)); then echo "yes"; else echo "no"; fi

字符串
上面的示例将回显no

相关问题