Why 'x' used in [ x“$VAR” = x“VALUE” ]?

2019-07-04 03:35发布

I can see in unix shell scripts that following construction used

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

instead of

[ "$VAR" = "VALUE" ] 

Why?

标签: shell unix
4条回答
The star\"
2楼-- · 2019-07-04 03:50

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.

查看更多
唯我独甜
3楼-- · 2019-07-04 03:59

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
查看更多
贪生不怕死
4楼-- · 2019-07-04 04:07

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

查看更多
Animai°情兽
5楼-- · 2019-07-04 04:10

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

查看更多
登录 后发表回答