-1
#!/bin/bash
STR1="David20"
STR2="fbhfthtrh"

if [ "$STR1"="$STR2" ]; then

        echo "Both the strings are equal"
else
        echo "Strings are not equal"
fi

1 Answers1

5

[ is a normal command (although a builtin) and the closing ] is just an argument to it. So is "$STR1"="$STR2" after the variables are expanded and quotes removed. The point is "$STR1"="$STR2" becomes one argument, and where there is just one argument before ] and it's a non-empty string, the result is true (exit status 0).

You want

[ "$STR1" = "$STR2" ]

Now there are three arguments before ] and the middle one (=) tells the command you want to compare strings.

  • Even with [[ (which isn't a normal command), [[ $a=$b ]] && echo yes always prints yes, for the same reason. – ilkkachu Feb 20 '20 at 22:05