/ bin / sh中的$ {1:+" $ @"}

时间:2020-03-06 14:56:34  来源:igfitidea点击:

我注意到有时包装程序脚本会使用$ {1:+" $ @"}作为参数,而不仅仅是" $ @"

例如,http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh使用

exec "$binary" $opts ${1:+"$@"}

任何人都可以将$ {1:+" $ @"}分解为英语,并解释为什么它比普通的" $ @"`有优势吗?

解决方案

从bash手册页:

${parameter:+word}
          Use Alternate Value.  If parameter is null or unset, nothing  is
          substituted, otherwise the expansion of word is substituted.

因此,除非未设置" $ 1",否则将替换" $ @"。我不明白为什么他们不能只使用" $ @"

"歇斯底里的葡萄干",又名历史原因。

JesperE(或者Bash手册页)中的解释准确地说明了它的作用:

如果$ 1存在并且不是空字符串,则替换引号中的参数列表。

大约在20年前,如果没有参数,Bourne Shell的一些破碎的次要变体将空字符串""替换为" $ @",而不是正确的当前行为,什么也没有替代。是否仍在使用这样的系统尚有争议。

[嗯:这种扩展不适用于以下情况:

command '' arg2 arg3 ...

在这种情况下,正确的符号是:

${1+"$@"}

不管$ 1是否为空参数,这都可以正常工作。因此,有人错误地记住了该表示法,偶然地引入了一个错误。]

为了引用乔纳森·勒夫勒在评论中提到的信息,请引用" man bash"的相关部分:

When not performing substring expansion, bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that is unset.

(强调我的)