#!/bin/bash
STR1="David20"
STR2="fbhfthtrh"
if [ "$STR1"="$STR2" ]; then
echo "Both the strings are equal"
else
echo "Strings are not equal"
fi
Asked
Active
Viewed 789 times
-1

ctrl-alt-delor
- 27,993
1 Answers
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.

Kamil Maciorowski
- 21,864
-
Even with
[[
(which isn't a normal command),[[ $a=$b ]] && echo yes
always printsyes
, for the same reason. – ilkkachu Feb 20 '20 at 22:05
"$STR1" = "$STR2"
– schrodingerscatcuriosity Feb 20 '20 at 20:26[[ ]]
, also use this site to validate your scripts. https://www.shellcheck.net/ – Jetchisel Feb 20 '20 at 20:28"$STR1"="$STR2"
is equivalent to"$STR1=$STR2"
. You need to delimit with space. – ctrl-alt-delor Feb 20 '20 at 20:31