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 ?

2
  • Does this answer your question? Compare a string using sh shell Commented Jun 21, 2021 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.) Commented Jun 21, 2021 at 13:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.