Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

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

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:

: ${SOMETHING='value'}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...