什么是外壳变量旁边的连字符 [英] What is a hyphen beside a shell variable

查看:31
本文介绍了什么是外壳变量旁边的连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些脚本中,我看到在shell变量上附加了一个连字符.例如:

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.

推荐答案

$ {parameter:-word}

如果未设置 parameter 或将其设置为null,则将替换 word 的扩展名.否则,将替换 parameter 的值.

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

就在这之前:

省略冒号只会对未设置的参数进行测试.

Omitting the colon results in a test only for a parameter that is unset.

所以:

${X-stuff}

扩展到:

  • 如果设置了 X ,则扩展 $ X
  • 东西(如果未设置 X ).
  • The expansion of $X if X is set
  • stuff if X is unset.

尝试一下:

$ unset X
$ echo "${X-stuff}"
stuff
$ X=
$ echo "${X-stuff}"

$ X=hello
$ echo "${X-stuff}"
hello
$

现在您的扩展名是

${X-}

因此,如果设置了 X ,则可能会扩展为 $ X 的扩展;如果未设置 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.

您为什么要这样做?对我来说,这似乎是 set -u :

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-}" ]

(请注意引号,它们是强制性的)测试 X 是否为nil(不管是否设置了 X ,即使 set -u ).

(note the quotes, they are mandatory) tests whether X is nil (regardless of X being set or not, even if set -u is used).

这篇关于什么是外壳变量旁边的连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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