“ ${ foo = value }”中冒号运算符的说明

我知道 bash 中冒号操作符的作用类似于 无效,我也知道它在 参数展开中被使用,也被用于其他方面,但有人能解释一下吗:

: ${SOMETHING='value'}

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

“因为它确实存在”是一个有效的答案,但是请指给我看它的文档(我似乎找不到) ,或者一个适当的名称来表示这种用法将是有用的。但我希望能有更有启发性的解释。

27550 次浏览

The expression ${SOMETHING='value'} sets SOMETHING to value if 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'}

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".

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.

Explained here : 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.