Bash中运算符"="和"=="之间有什么区别?

Deb*_*ger 61 bash operators

似乎这两个运营商几乎相同 - 有区别吗?我何时应该使用=何时==

Pau*_*ce. 82

您必须==在以下数字比较中使用(( ... )):

$ 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 ")
Run Code Online (Sandbox Code Playgroud)

您可使用在字符串比较[[ ... ]][ ... ]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
Run Code Online (Sandbox Code Playgroud)

"字符串比较?",你说?

$ 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
Run Code Online (Sandbox Code Playgroud)

  • 不过,你不应该将`==`与`[`或`test`一起使用.`==`不是POSIX规范的一部分,并且不适用于所有shell(`dash`,特别是,它不能识别它). (5认同)
  • @chepner:这是真的,但问题是关于Bash. (3认同)

gho*_*g74 29

关于POSIX有一个细微的差别.摘自Bash参考:

string1 == string2
如果字符串相等则为True. =可用于代替==严格的POSIX合规性.