在Bash中,"="和"=="操作符有什么区别?

63

看起来这两个运算符几乎相同 - 有什么区别吗?我何时应该使用 =,何时使用 ==

2个回答

85

(( ... )) 中进行数字比较时必须使用 ==

$ 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

6
不应该在使用[test命令时使用==,因为==并不属于POSIX规范的一部分,而且不是所有的shell都支持它(特别是dash不识别它)。 - chepner
3
没错,但问题特别涉及Bash。 - Dennis Williamson

30

在POSIX方面有一个微妙的区别,摘自Bash参考文档:

string1 == string2
如果字符串相等,则为True。为了严格遵守POSIX规范,可以使用=代替==


在Bash中没有任何区别吗?只是可移植性问题吗? - T.E.D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接