哪个更好用“==”或“-eq”来比较bash shell中的整数?

时间:2015-10-19 05:28:41

标签: bash shell

我可以看到像this这样的文章,其中提到“-eq”用于比较整数,但这并不是说我们不能使用“==”来比较整数。

我在本地bash shell上验证了这一点,“==”工作正常。 那么任何人都可以让我帮助理解哪个是更好的选择,如果“-eq”那么为什么呢?

2 个答案:

答案 0 :(得分:5)

要比较整数,请使用-eq。区别在于==比较字符串值,而-eq比较数值。这是一个产生不同结果的例子:

$ [ 03 = 3 ] ; echo $?
1
$ [ 03 -eq 3 ] ; echo $?
0

使用[[

是一样的
$ [[ 03 == 3 ]] ; echo $?
1
$ [[ 03 -eq 3 ]] ; echo $?
0

作为一个数字,03等于3。但是,字符串033不同。

摘要:要比较数字值是否相等,请使用-eq

答案 1 :(得分:2)

这取决于具体情况。在数学上下文中(如果您专门为bash编写脚本,这是最好的),请使用==

(( foo == 3 ))     ## foo = 3 would be an assignment here, and foo -eq 3 an error

在其他情况下也存在数学上下文 - 例如,索引到非关联数组,在下面的例子中使==首选但-eq非法:

foo=( yes no )
bar=3
echo "${foo[bar == 3 ? 0 : 1]}" # echoes "yes"

[[ ]]中,使用-eq

[[ $foo -eq 3 ]]   ## $foo = 3 would be a string comparison here; $foo == 3 is a synonym,
                   ## but bad finger-memory to have if one wants to write POSIX code
                   ## elsewhere.

[ ]中,使用-eq - 并引用:

[ "$foo" -eq 3 ]   ## = would be a valid string comparison here; == would be a
                   ## POSIX-incompatible string comparison here; -eq is correct.