Using null As a Valid Default Value

Problem

You need to set a default value, but you want to allow an empty string as a valid value. You only want to substitute the default in the case where the value is unset.

The ${:=} operator has two cases where the new value will be used: first, when the value of the shell variable has previously not been set (or has been explicitly unset); and second, where the value has been set but is empty, as in HOME="" or HOME=$OTHER (where $OTHER had no value).

Solution

The shell can distinguish between these two cases, and omitting the colon (:) indicates that you want to make the substitution only if the value is unset. If you write only ${HOME=/tmp} without the colon, the assignment will take place only in the case where the variable is not set (never set or explicitly unset).

Discussion

Let’s play with the $HOME variable again, but this time without the colon in the operator:

$ echo ${HOME=/tmp}  # no substitution needed
/home/uid002
$ HOME=""       # generally not wise
$ echo ${HOME=/tmp}  # will NOT substitute

$ unset HOME    # generally not wise
$ echo ${HOME=/tmp}     # will substitute
/tmp
$ echo $HOME
/tmp
$

In the case where we simply made the $HOME variable an empty string, the = operator didn’t do the substitution since $HOME did have a value, albeit null. But when we unset the variable, the substitution occurs. If you want to allow for empty strings, use just the = with no colon. Most times, though, the := is used because you can do little with an empty value, ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.