Tom Hale Tom Hale - 3 months ago 13
Bash Question

shell: What is the purpose of ${var:-} when var is unset or null?

In my Linux Mint 17.2

I see the following:



# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi


This is the first reference to the token
debian_chroot
.

Why does this code use
${debian_chroot:-}
instead of just
$debian_chroot
?

Bash's Shell Parameter Expansion says:


${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.


Here, "word" is null, so why bother substituting null for null?

Answer

The syntax ${debian_chroot:-} prevents the shell from exiting if it is running with set -u (crash when using undefined variables) and debian_chroot is unset at that point.

You don't want a normal interactive shell to have set -u (it would crash too easily), but it can be very useful in scripts.

To see this:

bash -c 'set -u; [ -z $a ]; echo ok'          # error
bash -c 'set -u; a=; [ -z $a ]; echo ok'      # ok
bash -c 'set -u; [ -z ${a:-} ]; echo ok'      # ok
bash -c 'set -u; a=; [ -z ${a:-} ]; echo ok'  # ok
Comments