看起来这两个运算符几乎相同 - 有什么区别吗?我何时应该使用 =
,何时使用 ==
?
在 (( ... ))
中进行数字比较时必须使用 ==
:
$ if (( 3 == 3 )); then echo "yes"; fi
yes
$ if (( 3 = 3 )); then echo "yes"; fi
bash: ((: 3 = 3 : attempted assignment to non-variable (error token is "= 3 ")
您可以在 [[ ... ]]
, [ ... ]
和 test
中使用以下任意一种进行字符串比较:$ if [[ 3 == 3 ]]; then echo "yes"; fi
yes
$ if [[ 3 = 3 ]]; then echo "yes"; fi
yes
$ if [ 3 == 3 ]; then echo "yes"; fi
yes
$ if [ 3 = 3 ]; then echo "yes"; fi
yes
$ if test 3 == 3; then echo "yes"; fi
yes
$ if test 3 = 3; then echo "yes"; fi
yes
"你说的是字符串比较吗?"
$ if [[ 10 < 2 ]]; then echo "yes"; fi # string comparison
yes
$ if (( 10 < 2 )); then echo "yes"; else echo "no"; fi # numeric comparison
no
$ if [[ 10 -lt 2 ]]; then echo "yes"; else echo "no"; fi # numeric comparison
no
在POSIX方面有一个微妙的区别,摘自Bash参考文档:
string1 == string2
如果字符串相等,则为True。为了严格遵守POSIX规范,可以使用=
代替==
。
[
或test
命令时使用==
,因为==
并不属于POSIX规范的一部分,而且不是所有的shell都支持它(特别是dash
不识别它)。 - chepner