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

时间:2010-04-08 13:40:43

标签: bash operators

这两个运营商似乎差不多 - 有区别吗?我应该何时使用===

2 个答案:

答案 0 :(得分:79)

您必须在==

中的数字比较中使用(( ... ))
$ 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

答案 1 :(得分:29)

与POSIX有细微差别。摘录自Bash reference

  

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

相关问题