Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash verbose string comparison slashes

I am comparing two strings in a bash script as follows:

x="hello"
y="hello"

if [[ "$x" != "$y" ]]; then
    echo "different"
else
    echo "same"
fi

This comparison works. When I execute the script with -x, the comparison still works, but it shows the output

+ x=hello
+ y=hello
+ [[ -n hello ]]
+ [[ hello != \h\e\l\l\o ]]
+ echo same

I'm curious why the right side of the string shows as\h\e\l\l\o and not hello

like image 777
Jeff Storey Avatar asked Nov 03 '14 17:11

Jeff Storey


1 Answers

The simple explanation is for the same reason that the left-hand side doesn't have quotes around it.

-x is showing you an equivalent but not exact representation of what it ran. The right-hand side of = and != in [[ ... ]] is matched as a pattern.

From the manual:

When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching. .... Any part of the pattern may be quoted to force it to be matched as a string.

The -x output, for some reason, chooses to use escaping instead quoting to disable pattern matching there.

like image 144
Etan Reisner Avatar answered Nov 15 '22 13:11

Etan Reisner