这两个运营商似乎差不多 - 有区别吗?我应该何时使用=
和==
?
答案 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。