It seems that these two operators are pretty much the same - is there a difference? When should I use =
and when ==
?
views:
132answers:
3
+5
A:
There's a subtle difference with regards to POSIX. Excerpt from the Bash reference:
string1 == string2
True if the strings are equal.=
may be used in place of==
for strict POSIX compliance.
ghostdog74
2010-04-08 13:53:59
+1 for finding a difference!
Dominic Rodger
2010-04-08 14:01:46
No difference in bash though? Just a portability issue?
T.E.D.
2010-04-08 14:11:26
@T.E.D.: No, see my answer.
Dennis Williamson
2010-04-08 16:19:13
+6
A:
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
:
$ 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
Dennis Williamson
2010-04-08 16:16:37
A:
I've never run into problems using = for comparisons, but then again I use -eq, -ne, -lt, -le, -gt, and -ge for numeric comparisons.
amertune
2010-04-09 03:50:30