92

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.

1
  • 2
    Note that the : built-in exists in bourne shell and ksh as well as bash.
    – ghoti
    Sep 13, 2012 at 11:02

2 Answers 2

120

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.

4
  • 13
    The : builtin command is documented here. It is also a POSIX standard. Apr 30, 2013 at 18:19
  • 3
    Also explained here.
    – x-yuri
    May 9, 2015 at 16:34
  • 5
    is there any difference between : ${SOMETHING="$HMMM"} and : ${SOMETHING:="$HMMM"} ? note second colon in the last example Apr 8, 2020 at 3:26
  • 7
    @YuryKozlov The first variation (=) will use the default value if the parameter is unset; the latter (:=) will use the default if the parameter is null or unset
    – Dave L.
    Aug 6, 2020 at 18:32
7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.