2010-04-08 14 views

risposta

71

È necessario utilizzare == a confronti numerici 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 ") 

è possibile utilizzare sia per i confronti tra stringhe nelle [[ ... ]] o [ ... ] o 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 

"I confronti di stringhe?", tu dici?

$ 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

Non dovresti usare '==' con '[' o 'test', però. '==' non fa parte delle specifiche POSIX e non funzionerà con tutte le shell ('dash', in particolare, non lo riconosce). – chepner

+3

@chepner: È vero, ma la domanda riguarda specificamente Bash. –

29

C'è una sottile differenza rispetto a POSIX. Estratto dal Bash reference:

string1 == string2
Vero se le stringhe sono uguali. = può essere utilizzato al posto di == per la stretta conformità POSIX.

+0

Nessuna differenza in bash? Solo un problema di portabilità? –

+0

@ T.E.D .: No, vedere la mia risposta. –

Problemi correlati