0

I just want to comparate 2 strings in shell. Here is the code below :

test1="tata"
test2="toto"
if [ $test1=$test2 ]
then
 echo "equal"
else
    echo "not equal"
fi

It must be return "not equal" but it returns "equal" whatever i'm writting in test1 and test2...

i've tried with those conditions below too:

if [[ $test1==$test2 ]] 
if [[ "$test1"=="$test2" ]]
if [ "$test1"="$test2" ]

but it does the same...

I'm just gonna get made!

Can somebody help me ?

Lye
  • 15
  • 3
  • Does this answer your question? [Compare a string using sh shell](https://stackoverflow.com/questions/10849297/compare-a-string-using-sh-shell) – 0stone0 Jun 21 '21 at 13:43
  • I don't think any of the answers in the proposed duplicate explicitly mention the issue here, which is the failure to make the operator and the two operands distinct words. (Ah, the second one does.) – chepner Jun 21 '21 at 13:43

1 Answers1

1

The spaces around = or == are not optional:

if [[ $test1 == $test2 ]] 
if [[ "$test1" == "$test2" ]]
if [ "$test1" = "$test2" ]

Without the spaces, you have a single word that happens to contain = or ==, which means both commands are simply checking if that word is the empty string or not. Any string containing at least one = is clearly not empty, so the entire command succeeds. ([ foo ] is equivalent to [ -n foo ].

chepner
  • 497,756
  • 71
  • 530
  • 681