shell 变量旁边的连字符是什么

What is a hyphen beside a shell variable

我在我们的一些脚本中看到 shell 变量附加了一个连字符。例如:

if [ -z ${X-} ]

变量旁边的这个连字符在这里有什么作用。 我找不到任何在线文档。

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.

在此之前有:

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

所以:

${X-stuff}

扩展为:

  • $X的扩展如果设置了X
  • stuff 如果 X 未设置。

试一试:

$ 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 是否为 nil(无论是否设置 X,即使使用 set -u)。