bash ": ${foo=value}" 中冒号运算符的解释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7444504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:47:52  来源:igfitidea点击:

Explanation of colon operator in ": ${foo=value}"

bash

提问by Peter Coulton

I understand the colon operator in bash that acts like a null, and I know it's used in parameter expansion, as well as being used other ways, but can someone explain this:

我了解 bash 中的冒号运算符,它的作用类似于null,并且我知道它用于参数扩展以及其他方式,但有人可以解释一下:

: ${SOMETHING='value'}

From experimentation I know that this sets the environment variable $SOMETHINGto 'value'but why?

从实验中我知道这将环境变量设置为$SOMETHING'value'但为什么呢?

"Just because it does" is a valid answer but then please point me to the documentation for it (which I can't seem to find) or a proper name for this usage would be useful. I'm hoping there's a more enlightening explanation though.

“只是因为它确实”是一个有效的答案,但请指出它的文档(我似乎找不到),或者这种用法的正确名称会很有用。不过,我希望有一个更有启发性的解释。

回答by Kilian Foth

The expression ${SOMETHING='value'}sets SOMETHING to valueif it isn't already set. This is a useful operator to have in many situations. However, it also returns the assigned value, so if you simply executed

如果尚未设置${SOMETHING='value'}value则表达式将 SOMETHING设置为。在许多情况下,这是一个有用的运算符。但是,它也会返回分配的值,因此如果您只是执行

${SOMETHING='value'}

then your shell would try to invoke the command value. This might or might not do something unwanted; at the least it would throw a message "value: command not found".

那么你的 shell 会尝试调用命令value。这可能会也可能不会做一些不需要的事情;至少它会抛出一条消息“值:未找到命令”。

To avoid this you can use the no-op :, which evaluates its argument and then throws it away, rather than executing it. This is documented here.

为了避免这种情况,您可以使用 no-op :,它会评估其参数,然后将其丢弃,而不是执行它。这在此处记录

回答by Arnaud F.

Explained here : http://tldp.org/LDP/abs/html/parameter-substitution.html

在这里解释:http: //tldp.org/LDP/abs/html/parameter-substitution.html

If parameter not set, set it to default.

Both forms nearly equivalent. The : makes a difference only when $parameter has been declared and is null, [1] as above.

echo ${var=abc}   # abc
echo ${var=xyz}   # abc
# $var had already been set to abc, so it did not change.

如果未设置参数,则将其设置为默认值。

两种形式几乎相同。: 仅当 $parameter 已声明且为空时才会有所不同,[1] 如上所述。

echo ${var=abc}   # abc
echo ${var=xyz}   # abc
# $var had already been set to abc, so it did not change.