1

After reading Debian's /usr/bin/startx, there was something I found peculiar:

mcookie=`/usr/bin/mcookie`

if test x"$mcookie" = x; then
    echo "Couldn't create cookie"
    exit 1
fi

I don't understand why the extra x is necessary - wouldn't it be equivalent to write the following?

mcookie=`/usr/bin/mcookie`

if test "$mcookie" = ""; then
    echo "Couldn't create cookie"
    exit 1
fi

I initially thought that very early versions of sh might have printed some error if the mkcookie variable happened to be unset (this wasn't the only instance; these types of comparisons were scattered liberally throughout the script). But then it didn't make much sense after further thought because the variable was being quoted and the shell would expand it to an empty string.

I perused the Dash, --posix section of the Bash man page and checked POSIX itself. It said nothing about it under test: s1 = s2 True if the strings s1 and s2 are identical; otherwise, false. I assume the people that wrote the script knew what they were doing - so can someone shed some light on this?

Thankies, Edwin

hyperupcall
  • 869
  • 10
  • 21

1 Answers1

4

Here's an excerpt from the Wooledge Bash Pitfall #4:

You may have seen code like this:

[ x"$foo" = xbar ] # Ok, but usually unnecessary.

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 -. On said older systems, [ still doesn't care whether the token on the right hand side of the = begins with a -. It just uses it literally. It's just the left-hand side that needs extra caution.

Note that shells that require this workaround are not POSIX-conforming. Even the Heirloom Bourne shell doesn't require this (probably the non-POSIX Bourne shell clone that's still most widely in use as a system shell). Such extreme portability is rarely a requirement and makes your code less readable (and uglier).

If you find it in code from this century, it's just cargo culting that keeps being reinforced by people who don't quote.

/usr/bin/startx in particular has used this idiom since at least XFree86 2.1 in Feb 1993, and any updates have likely just matched style since.

that other guy
  • 116,971
  • 11
  • 170
  • 194