Tom Hale Tom Hale - 2 months ago 5x
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)

This is the first reference to the token

Why does this code use
instead of just

Bash's Shell Parameter Expansion says:


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?


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