user4385532
user4385532

Reputation:

Why do two empty strings compare as not equal?

my@comp:~/wtfdir$ cat wtf.sh
str1=$(echo "")
str2=$(echo "")

if [ $str1 != $str2 ]; then
  echo "WTF?!?!"
fi
my@comp:~/wtfdir$ ./wtf.sh
WTF?!?!
my@comp:~/wtfdir$

WTF is going on here?!

How I wrote the above code: Googling "bash compare strings" brought me to this website which says:

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!=” is used to check inequality of the strings.

Yet I'm getting the above?

What am I not understanding? What am I doing wrong?

Upvotes: 2

Views: 2787

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295679

You aren't running a comparison at all, because you aren't using quotes where they're mandatory. See the warning from http://shellcheck.net/ about unquoted expansions at SC2086.

If both string are empty, then:

[ $str1 != $str2 ]

...evaluates to...

[ != ]

...which is a test for whether the string != is nonempty, which is true. Change your code to:

[ "$str1" != "$str2" ]

...and the exact values of those strings will actually be passed through to the [ command.


Another alternative is using [[; as described in BashFAQ #31 and the conditional expression page on the bash-hackers' wiki, this is extended shell syntax (in ksh, bash, and other common shells extending the POSIX sh standard) which suppresses the string-splitting behavior that's tripping you up:

[[ $str1 != "$str2" ]]

...requires quotes only on the right-hand side, and even those aren't needed for the empty-string case, but to prevent that right-hand side from being treated as a glob (causing the comparison to always reflect a match if str2='*').

Upvotes: 11

Related Questions