#!/bin/bash
STR1="David20"
STR2="fbhfthtrh"
if [ "$STR1"="$STR2" ]; then
echo "Both the strings are equal"
else
echo "Strings are not equal"
fi
1 Answer
[ 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 yesalways printsyes, for the same reason.ilkkachu– ilkkachu2020-02-20 22:05:44 +00:00Commented Feb 20, 2020 at 22:05
"$STR1" = "$STR2"[[ ]], also use this site to validate your scripts. shellcheck.net"$STR1"="$STR2"is equivalent to"$STR1=$STR2". You need to delimit with space.