2010-04-08 140 views

回答

71

您必须((...))在数字比较使用==

$ 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 
+3

尽管如此,你不应该在''''或'test'中使用'=='。 '=='不是POSIX规范的一部分,并且不适用于所有shell('dash',特别是不能识别它)。 – chepner 2015-11-10 19:39:38

+3

@chepner:这是真的,但问题是关于Bash的具体问题。 – 2015-11-10 20:01:25

29

关于POSIX有一个细微的差别。从Bash reference摘录:

string1 == string2
True如果字符串相等。可以使用=来代替==以符合严格的POSIX标准。

+0

bash虽然没有区别吗?只是一个可移植性问题? – 2010-04-08 14:11:26

+0

@ T.E.D .:不,请参阅我的答案。 – 2010-04-08 16:19:13

相关问题