2010-04-08 62 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

相關問題