synapse
synapse

Reputation: 5728

String comparison doesn't work

For some reason this script prints "string are equal"

#!/bin/bash
A='foo'
B='bar'

if [ $A=$B ];
then
  echo 'strings are equal' 
fi

What am I doing wrong?

Upvotes: 9

Views: 2087

Answers (2)

Teddy
Teddy

Reputation: 6163

You're supposed to have spaces around the equals character:

if [ $A = $B ];
       ^ ^
      There

Also, you ought to quote the variables, like this:

if [ "$A" = "$B" ];

Upvotes: 7

bmk
bmk

Reputation: 14137

You have to leave a space around the equal sign:

if [ "$A" = "$B" ];
then
  echo 'strings are equal' 
fi

Edit: Please notice also the quotation marks around the variables. Without them you will get into trouble if one of them is empty.

Otherwise the test is interpreted as test if the string "foo=bar" has a length>0.
See man test:

   ...
   STRING equivalent to -n STRING
   -n STRING
          the length of STRING is nonzero
   ...

Upvotes: 16

Related Questions