为什么shell脚本比较经常使用x$VAR = xyes? [英] Why do shell script comparisons often use x$VAR = xyes?

查看:32
本文介绍了为什么shell脚本比较经常使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆