Bash 中的运算符“=”和“==”有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2600281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between operator "=" and "==" in Bash?
提问by Debugger
It seems that these two operators are pretty much the same - is there a difference? When should I use =and when ==?
似乎这两个运营商几乎相同 - 有区别吗?我应该什么时候使用=,什么时候使用==?
回答by Paused until further notice.
You must use ==in numeric comparisons in (( ... )):
您必须==在以下数字比较中使用(( ... )):
$ 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 ")
You may use either for string comparisons in [[ ... ]]or [ ... ]or test:
您可以在[[ ... ]]or[ ... ]或 中用于字符串比较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
"String comparisons?", you say?
“字符串比较?”,你说?
$ 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
回答by ghostdog74
There's a subtle difference with regards to POSIX. Excerpt from the Bash reference:
POSIX 有细微的差别。摘自Bash 参考:
string1 == string2
True if the strings are equal.=may be used in place of==for strict POSIX compliance.
string1 == string2
如果字符串相等,则为真。=可用于代替==严格的 POSIX 合规性。

