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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With