shell变量旁边的连字符是什么(What is a hyphen beside a shell variable)

编程入门 行业动态 更新时间:2024-10-21 09:22:38
shell变量旁边的连字符是什么(What is a hyphen beside a shell variable)

我在一些脚本中看到有一个连接到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).

更多推荐

本文发布于:2023-08-06 14:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451209.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   字符   shell   hyphen   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!