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

I understand the colon operator in bash, which acts like null , and I know that it was used in parameter expansion , and is also used in other ways, but can someone explain this:

: ${SOMETHING='value'} 

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

β€œJust because he does this” is a valid answer, but then please give me the documentation for it (which I cannot find), or a suitable name for this use would be helpful. I hope there will be a more enlightening explanation.

+59
bash
Sep 16 '11 at 12:14
source share
2 answers

The expression sets SOMETHING to value , if not already set. This is a useful operator in many situations. However, it also returns the assigned value, so if you just performed

 ${SOMETHING='value'} 

then your shell will try to call the value command. It may or may not do something undesirable; at least he would throw out the message "value: command not found".

To avoid this, you can use no-op : which evaluates its argument and then discards it rather than executing it.

+65
Sep 16 '11 at 12:20
source share

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

If not set, set it by default.

Both forms are almost equivalent. The: only matters when $ was declared and is zero, [1] as above.

 echo ${var=abc} # abc echo ${var=xyz} # abc # $var had already been set to abc, so it did not change. 
+6
Sep 16 '11 at 12:21
source share



All Articles