Home > database >  Why add a placeholder alongside bash variable checks?
Why add a placeholder alongside bash variable checks?

Time:01-24

I've seen many shell scripts that examine the input args using a comparison to a placeholder string, e.g.

if
[ "x$1" == "x" ]; then
xyz()
fi

I'm assuming this to be a best practice, because of how ubiquitous it seems to be.

Personally, I've always done an input arg examination without placeholders:

if
[ "$1" == "" ]; then
xyz()
fi

What is the reason for using the placeholder? What potential pitfalls are avoided using that syntax?

CodePudding user response:

There's a partial explanation on the Bash wiki under pitfall 4.

The x"$foo" hack is required for code that must run on very ancient shells which lack [[ and have a more primitive [, which gets confused if $foo begins with a - or is ! or (. On said older systems, [ only requires extra caution for the token on the left-hand side of =; it handles the right-hand token correctly.

You should ideally never need to do this for a shell script you write today, but it's good to understand why older shell scripts do it sometimes.

  • Related