rophl
rophl

Reputation: 187

Why does this bash script add a letter before comparing?

I have a script here that includes this snippet:

read -p ">" DEPLOY_CONFIRM
if [ "xy" != "x$DEPLOY_CONFIRM" ] ; then
  .. snip ..
fi

Is adding the x before doing the comparison important? My guess is it guards against the user entering something that starts with a funny character.

Upvotes: 2

Views: 75

Answers (2)

Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

You can always use the double quotes while comparing the string which always wont give any syntax errors.

[ "y" = "$s" ] && echo "matched"

Upvotes: 0

anubhava
anubhava

Reputation: 785256

Prefixing each variable and literal with a known constant literal x was done in old shell scripts while using unquoted variable to safeguard again error like unary operator expected.

As long as you're using quoted variables you don't need this trick of prefixing x.

So you could very well use this in BASH:

read -p ">" DEPLOY_CONFIRM
if [[ "$DEPLOY_CONFIRM" == [Yy] ]]; then
  .. snip ..
fi

To generate this error use snippet like this:

unset s
[ "y" = $s ] && echo "matched"
-bash: [: y: unary operator expected

And then see improved behavior with prefixing with x:

[ "xy" = x$s ] && echo "matched"

Upvotes: 4

Related Questions