What is the difference between operator "=" and "==" in Bash?

BashOperators

Bash Problem Overview


It seems that these two operators are pretty much the same - is there a difference? When should I use = and when ==?

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDebuggerView Question on Stackoverflow
Solution 1 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 2 - Bashghostdog74View Answer on Stackoverflow