Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 740
ibrahim Avatar asked Oct 18 '12 06:10

ibrahim


2 Answers

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.

like image 151
sampson-chen Avatar answered Oct 23 '22 08:10

sampson-chen


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

like image 26
doubleDown Avatar answered Oct 23 '22 09:10

doubleDown