#!/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 557 times
-1
ctrl-alt-delor
- 27,473
- 9
- 58
- 102
-
3You need a space both sides of the equal sign: `"$STR1" = "$STR2"` – schrodingerscatcuriosity Feb 20 '20 at 20:26
-
in bash use `[[ ]]`, 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
-
Got it. Thanks @ Kamil Maciorowski – user396509 Feb 20 '20 at 20:50
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
- 19,242
- 1
- 50
- 94
-
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