为什么Shell脚本比较经常使用x $ VAR = xyes? [英] Why do shell script comparisons often use x$VAR = xyes?
问题描述
我经常在使用自动工具(autoconf,automake)的项目的构建脚本中看到这种情况.当有人要检查shell变量的值时,他们经常使用以下成语:
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.
推荐答案
如果您使用的是执行简单替换的shell,并且SHELL_VAR
变量不存在(或为空),那么您需要提防边缘情况.以下翻译将会发生:
If you're using a shell that does simple substitution and the SHELL_VAR
variable does not exist (or is blank), then you need to watch out for the edge cases. The following translations will happen:
if test $SHELL_VAR = yes; then --> if test = yes; then
if test x$SHELL_VAR = xyes; then --> if test x = xyes; then
由于test
的第一个参数丢失,第一个会产生错误.第二个没有这个问题.
The first of these will generate an error since the fist argument to test
has gone missing. The second does not have that problem.
您的案例翻译如下:
if test "x$SHELL_VAR" = "xyes"; then --> if test "x" = "xyes"; then
x
至少对于POSIX兼容的shell实际上是多余的,因为引号确保将一个空参数和一个包含空格的参数都解释为单个对象.
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.
这篇关于为什么Shell脚本比较经常使用x $ VAR = xyes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!