views:

77

answers:

5

I can see in unix shell scripts that following construction used

[ x"$VAR" = x"VALUE" ] 

instead of

[ "$VAR" = "VALUE" ] 

Why?

+4  A: 

when $VAR is empty it would give a syntax error [ = "VALUE"], thus the usage of x

knittl
Beat me by 9 seconds.
Paul Tomblin
Yup. If you're interested in learning a lot of little things like this in advance, rather than as you stumble across them, I'd personally recommend the O'Reilly book *Classic Shell Scripting*, see http://oreilly.com/catalog/9780596005955 . A lot of the more obscure bits of shell scripts became a lot more comprehensible once I'd read this.
Matt Gibson
A: 

Because if either $VAR or VALUE is empty, you get a nasty error if you don't use the "x".

Paul Tomblin
But I use quotes.
Vladimir Bezugliy
@Vladimir, sometimes the shell swallows the quotes.
Paul Tomblin
+5  A: 

Because shells were not always entirely well-behaved if one of the variables was empty.

Consider if $VAR was empty/null and $VALUE is "foo", your two constructs expand to:

[ x = xfoo ]

and

[ = foo ]

The latter would cause an error in some shells due to being an illegal construct, while the former is valid in any case. This is not a problem in recent version of bash (perhaps even old versions of bash) but that's where it comes from historically - and asides from the occasional moment of puzzlement from people in your situation, there's little reason not to do it for compatibility with a wider range of shells.

Andrzej Doyle
There are quotes in my example.I said [ "x" = x"foo" ] not [ x = xfoo ]
Vladimir Bezugliy
With quotes (and modern shells), you don't need the 'x' -- `[ "$var" = "val" ]` becomes, when var is empty: `[ "" = "val" ]` which is simply false with no errors.
glenn jackman
+1  A: 

This is an old technique to prevent either side of the comparison from being empty. Some shells don't handle empty strings properly.

Frerich Raabe
What shells do you mean?
Vladimir Bezugliy
@Vladimir: According to http://tldp.org/LDP/abs/html/comparison-ops.html (see the footnote), some older Bash versions don't handle empty strings correctly.
Frerich Raabe
A: 

you have got your explanations, but here's another approach, using case/esac instead of if/else

case "$VAR" in 
  "$VALUE" ) echo 'yes';;
  * ) echo 'no' ;;
esac
ghostdog74