I see this often in the build scripts of projects that use autotools (autoconf, automake). When somebody wants to check the value of a shell variable, they frequently use this idiom:
if test 'x$SHELL_VAR' = 'xyes'; then ...
What is the advantage to this over simply checking the value like this:
if test $SHELL_VAR = 'yes'; then ...
I figure there must be some reason that I see this so often, but I can’t figure out what it is.
If you’re using a shell that does simple substitution and the
SHELL_VARvariable does not exist (or is blank), then you need to watch out for the edge cases. The following translations will happen:The first of these will generate an error since the fist argument to
testhas gone missing. The second does not have that problem.Your case translates as follows:
The
x, at least for POSIX-compliant shells, is actually redundant since the quotes ensue that both an empty argument and one containing spaces are interpreted as a single object.