It seems that these two operators are pretty much the same - is there a difference? When should I use =
and when ==
?
Inside single brackets for condition test (i.e. [ ... ]), single = is supported by all shells, where as == is not supported by some of the older shells. Inside double brackets for condition test (i.e. [[ ... ]]), there is no difference in old or new shells. Show activity on this post.
== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.
Double Brackets i.e. [[]] is an enhanced (or extension) version of standard POSIX version, this is supported by bash and other shells(zsh,ksh). In bash, for numeric comparison we use eq , ne , lt and gt , with double brackets for comparison we can use == , !=
Linux Bash scripting language provides the not equal “-ne” operator in order to compare two values if they are not equal. The not equal operator generally used with the if or elif statements to check not equal and execute some commands.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With