Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison doesn't work

Tags:

bash

shell

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?

like image 787
synapse Avatar asked Jun 14 '11 09:06

synapse


Video Answer


2 Answers

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
   ...
like image 68
bmk Avatar answered Sep 23 '22 15:09

bmk


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" ];
like image 33
Teddy Avatar answered Sep 19 '22 15:09

Teddy