问题描述
我可以在 unix shell 脚本中看到以下使用的构造
I can see in unix shell scripts that following construction used
[ x"$VAR" = x"VALUE" ]
代替
[ "$VAR" = "VALUE" ]
为什么?
推荐答案
因为如果其中一个变量为空,shell 并不总是完全表现良好.
Because shells were not always entirely well-behaved if one of the variables was empty.
考虑如果 $VAR
为空/null 并且 $VALUE
是foo",你的两个结构扩展为:
Consider if $VAR
was empty/null and $VALUE
is "foo", your two constructs expand to:
[ x = xfoo ]
和
[ = foo ]
后者会因为是非法构造而在某些shell中导致错误,而前者在任何情况下都是有效的.这在最新版本的 bash(甚至可能是旧版本的 bash)中不是问题,但这就是它的历史来源-除了偶尔会遇到遇到您情况的人感到困惑之外,几乎没有理由不 这样做是为了与更广泛的 shell 兼容.
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.
这篇关于为什么在[ x“$VAR"中使用'x'?= x“值"]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!