Sembra che questi due operatori siano praticamente uguali: c'è una differenza? Quando dovrei usare =
e quando ==
?Qual è la differenza tra l'operatore "=" e "==" in Bash?
risposta
È 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
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.
Nessuna differenza in bash? Solo un problema di portabilità? –
@ T.E.D .: No, vedere la mia risposta. –
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
@chepner: È vero, ma la domanda riguarda specificamente Bash. –