Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

bash

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

like image 360
Debugger Avatar asked Apr 08 '10 13:04

Debugger


People also ask

What is the difference between and == in bash?

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.

What does == mean in bash?

== 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.

What is the difference between using and == In a bash double square bracket if conditional?

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 == , !=

Can I use != In bash?

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.


2 Answers

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 
like image 196
Dennis Williamson Avatar answered Sep 30 '22 17:09

Dennis Williamson


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.

like image 25
ghostdog74 Avatar answered Sep 30 '22 17:09

ghostdog74