【发布时间】:2010-04-08 13:40:42
【问题描述】:
这两个运算符似乎几乎相同 - 有区别吗?我应该什么时候使用=,什么时候使用==?
【问题讨论】:
这两个运算符似乎几乎相同 - 有区别吗?我应该什么时候使用=,什么时候使用==?
【问题讨论】:
您必须在(( ... )) 的数字比较中使用==:
$ 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
【讨论】:
== 与[ 或test 一起使用。 == 不是 POSIX 规范的一部分,并且不适用于所有 shell(尤其是 dash,无法识别它)。
在 POSIX 方面存在细微差别。摘自Bash reference:
string1 == string2
如果字符串相等,则为真。=可以用来代替==以严格遵守 POSIX。
【讨论】: