我在一些脚本中看到有一个连接到shell变量的连字符。 例如:
if [ -z ${X-} ]变量旁边的这个连字符符号在这里做了什么。 我在网上找不到任何相关文档。
I saw in some of our scripts that there is a hyphen attached to a shell variable. For example:
if [ -z ${X-} ]What does this hyphen symbol beside the variable do here. I cannot find any documentation online for this.
最满意答案
这一切都在本手册的Shell参数扩展部分中进行了解释:
${parameter:-word}
如果parameter未设置或为null,则替换word的扩展。 否则, parameter的值将被替换。
就在此之前,有:
省略冒号只会导致对未设置的参数进行测试。
所以:
${X-stuff}扩展为:
如果设置$X则扩展$X 如果X没有设置的stuff 。尝试一下:
$ unset X $ echo "${X-stuff}" stuff $ X= $ echo "${X-stuff}" $ X=hello $ echo "${X-stuff}" hello $现在你的扩张是
${X-}因此,如果设置$X ,它会扩展到$X的扩展,如果未设置$X ,则扩展为空字符串。
你为什么想做这个? 对我来说,似乎这是一个解决方法set -u :
$ set -u $ unset X $ echo "$X" bash: X: unbound variable $ echo "${X-}" $最后,你的测试
if [ -z "${X-}" ](注意引号,它们是必需的)测试X是否为零(无论是否设置X ,即使使用了set -u )。
It's all explained in the Shell Parameter Expansion section of the manual:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
Just before this there is:
Omitting the colon results in a test only for a parameter that is unset.
So:
${X-stuff}expands to:
The expansion of $X if X is set stuff if X is unset.Try it:
$ unset X $ echo "${X-stuff}" stuff $ X= $ echo "${X-stuff}" $ X=hello $ echo "${X-stuff}" hello $Now your expansion is
${X-}so you guess that it expands to the expansion of $X if X is set, and to the null string if X is unset.
Why would you want to do this? to me it seems that this is a workaround the set -u:
$ set -u $ unset X $ echo "$X" bash: X: unbound variable $ echo "${X-}" $Finally, your test
if [ -z "${X-}" ](note the quotes, they are mandatory) tests whether X is nil (regardless of X being set or not, even if set -u is used).
更多推荐
发布评论