ibrahim
ibrahim

Reputation: 3414

Is there any difference between '=' and '==' operators in bash or sh

I realized that both '=' and '==' operators works in if statement. For example:

var="some string"
if [ "$var" == "some string" ];then
    #doing something
fi

if [ "$var" = "some string" ];then
    #doing something
fi

Both if statement above worked well in bash and sh. I just wondered if there is any difference between them? Thanks...

Upvotes: 5

Views: 8148

Answers (2)

doubleDown
doubleDown

Reputation: 8408

They're different in arithmetic evaluation

Within double parentheses, = cannot be used for comparison whereas == works fine, e.g.

(( $var == 3 )) works fine

(( $var = 3 )) gives error (comparison).

(( var = 3 )) works (assignment), but this always evaluates to TRUE

Upvotes: 1

sampson-chen
sampson-chen

Reputation: 47267

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.

Edit: I should also note that: Always use double brackets [[ ... ]] if possible, because it is safer than single brackets. I'll illustrate why with the following example:

if [ $var == "hello" ]; then

if $var happens to be null / empty, then this is what the script sees:

if [ == "hello" ]; then

which will break your script. The solution is to either use double brackets, or always remember to put quotes around your variables ("$var"). Double brackets is better defensive coding practice.

Upvotes: 9

Related Questions