Default Values with Parameter Expansion
A parameter expansion is any place where Bash replaces $name or ${name} with a value. The braced form can do more than just insert a value: it can supply a fallback when the variable is missing, assign one, require that the variable exists, or substitute something else when it does. These forms let a script cope with missing input without writing a separate if statement every time.
Three States of a Variable
To understand the operators, first separate the situations in which a variable can be:
| State | Example | Meaning |
|---|---|---|
| Unset | unset name | The name does not exist |
| Empty (null) | name="" | The name exists and holds an empty string |
| Set and non-empty | name=Ana | The name holds a value |
Each of the operators below comes in two forms. With a colon (:-) the test is "unset or empty". Without the colon (-) the test is only "unset".
The Operators at a Glance
| Expansion | If the variable is unset | If empty | If non-empty |
|---|---|---|---|
${var:-word} | word | word | value |
${var-word} | word | empty | value |
${var:=word} | assigns word, gives word | assigns word, gives word | value |
${var=word} | assigns word, gives word | empty | value |
${var:?message} | prints message, stops | prints message, stops | value |
${var?message} | prints message, stops | empty | value |
${var:+word} | empty | empty | word |
${var+word} | empty | word | word |
The script below prints all four basic results (-, :-, +, :+) for a variable in each state. It uses ${!name}, which reads the variable whose name is stored in name, so one loop can handle all three variables:
cat > d1.sh <<'EOF'
unset unsetv
emptyv=""
filled=hello
for name in unsetv emptyv filled; do
echo "== $name"
echo " \${$name-fallback} -> [${!name-fallback}]"
echo " \${$name:-fallback} -> [${!name:-fallback}]"
echo " \${$name+alt} -> [${!name+alt}]"
echo " \${$name:+alt} -> [${!name:+alt}]"
done
EOF
bash d1.sh
== unsetv
${unsetv-fallback} -> [fallback]
${unsetv:-fallback} -> [fallback]
${unsetv+alt} -> []
${unsetv:+alt} -> []
== emptyv
${emptyv-fallback} -> []
${emptyv:-fallback} -> [fallback]
${emptyv+alt} -> [alt]
${emptyv:+alt} -> []
== filled
${filled-fallback} -> [hello]
${filled:-fallback} -> [hello]
${filled+alt} -> [alt]
${filled:+alt} -> [alt]
The only differences between the colon and non-colon forms appear in the middle block, for the empty variable. In everyday scripts the colon forms are usually what you want, because an empty value is rarely a useful value.
Using a Default: ${var:-word}
${var:-word} gives word when var is unset or empty, and gives the value of var otherwise. The variable itself is not changed:
cat > d2.sh <<'EOF'
unset name
echo "Hello, ${name:-stranger}!"
echo "name is still: [${name-<unset>}]"
name=Ana
echo "Hello, ${name:-stranger}!"
EOF
bash d2.sh
Hello, stranger!
name is still: [<unset>]
Hello, Ana!
The first greeting used the default, and the check on the next line proves that name was not created. Once name has a value, the default is ignored.
Defaults for Arguments
Because command-line arguments are positional parameters, they work with the same operators:
cat > d8.sh <<'EOF'
name=${1:-World}
echo "Hello, $name!"
echo "count=${2:-1}"
EOF
bash d8.sh
bash d8.sh Ana 3
bash d8.sh ""
Hello, World!
count=1
Hello, Ana!
count=3
Hello, World!
count=1
An empty argument ("") triggers the colon form, so the default applies there too.
Defaults for Environment Settings
Programs often let the caller override a setting through an environment variable and fall back to a built-in value:
cat > d14.sh <<'EOF'
port=${PORT:-8080}
echo "port=$port"
EOF
bash d14.sh
PORT=3000 bash d14.sh
PORT= bash d14.sh
port=8080
port=3000
port=8080
The third run set PORT to an empty string. Because the script used :-, an empty value was treated like a missing one. With ${PORT-8080} the third run would have produced an empty port.
The Default Can Be an Expansion
The word after the operator is expanded like any other text, so it can be a variable, a command substitution, or another default expression:
cat > nick.sh <<'EOF'
NICK=ana
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
USER_NAME=suriya
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
unset NICK USER_NAME
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
EOF
bash nick.sh
user=ana
user=suriya
user=unknown
The expression tries USER_NAME first, then NICK, and finally the literal word unknown. Writing a command substitution as the default also works, for example ${DATE:-$(date +%F)}. The command runs only when the default is actually needed.
Assigning a Default: ${var:=word}
${var:=word} works like :-, but it also stores word in the variable when the default is used:
cat > d3.sh <<'EOF'
unset dir
echo "dir before: [${dir-<unset>}]"
echo "using: ${dir:=/tmp/work}"
echo "dir after: [$dir]"
echo "second use: ${dir:=/other}"
EOF
bash d3.sh
dir before: [<unset>]
using: /tmp/work
dir after: [/tmp/work]
second use: /tmp/work
The first expansion created dir. The second := found a value and left it alone.
The Colon Command Idiom
If you only want to ensure that a variable has a value and do not need to print it, the null command : is useful. It does nothing, but Bash still expands its arguments, so the assignment happens:
cat > d3b.sh <<'EOF'
: "${LOG_LEVEL:=info}"
echo "LOG_LEVEL=$LOG_LEVEL"
LOG_LEVEL=debug
: "${LOG_LEVEL:=info}"
echo "LOG_LEVEL=$LOG_LEVEL"
EOF
bash d3b.sh
LOG_LEVEL=info
LOG_LEVEL=debug
The first : line set the missing variable, and the second left debug untouched. The quotes protect the value from word splitting.
The Difference Between = and :=
cat > d4.sh <<'EOF'
empty=""
echo "[${empty=filled}]"
echo "[${empty:=filled}]"
echo "empty now: [$empty]"
EOF
bash d4.sh
[]
[filled]
empty now: [filled]
Without the colon, an empty-but-set variable is accepted as it is. With the colon, it is replaced.
Positional Parameters Cannot Be Assigned
The := form assigns to a real variable, so it is not allowed for $1, $2 and the other positional parameters:
cat > d9.sh <<'EOF'
echo "${1:=x}"
echo "status=$?"
EOF
bash d9.sh
d9.sh: line 1: $1: cannot assign in this way
status=1
Use ${1:-x} to read a default, or copy the argument into a normal variable first, as d8.sh did with name=${1:-World}.
Requiring a Value: ${var:?message}
${var:?message} stops the script with an error when the variable is unset or empty. It is a compact way to say "this must be provided":
cat > d5.sh <<'EOF'
unset TARGET
echo "start"
echo "target is ${TARGET:?TARGET must be set}"
echo "never printed"
EOF
bash d5.sh
echo "exit=$?"
start
d5.sh: line 3: TARGET: TARGET must be set
exit=1
Bash printed the variable name and the message to standard error, and the non-interactive script ended with exit status 1, so the last echo never ran. If you leave the message out, Bash supplies a default one:
cat > d6.sh <<'EOF'
unset TARGET
: "${TARGET:?}"
echo "never printed"
EOF
bash d6.sh
echo "exit=$?"
d6.sh: line 2: TARGET: parameter null or not set
exit=1
The colon decides whether an empty value counts as missing:
cat > d7.sh <<'EOF'
TARGET=""
: "${TARGET:?TARGET is empty or unset}"
echo x
EOF
bash d7.sh
echo "exit=$?"
cat > d7b.sh <<'EOF'
TARGET=""
: "${TARGET?TARGET is unset}"
echo "no colon: empty is accepted"
EOF
bash d7b.sh
echo "exit=$?"
d7.sh: line 2: TARGET: TARGET is empty or unset
exit=1
no colon: empty is accepted
exit=0
In an interactive terminal the same error prints a message but does not close your shell. The "stop the script" behavior applies to scripts.
Using an Alternative Value: ${var:+word}
${var:+word} is the opposite of :-. It gives word only when the variable has a value, and gives nothing otherwise. It is handy for adding an optional piece of text or an option:
cat > d10.sh <<'EOF'
verbose=1
echo "flag:${verbose:+ --verbose}"
unset verbose
echo "flag:${verbose:+ --verbose}"
name=Ana
echo "Dear ${name}${title:+, $title}"
title=Dr
echo "Dear ${name}${title:+, $title}"
EOF
bash d10.sh
flag: --verbose
flag:
Dear Ana
Dear Ana, Dr
The text after :+ appears only when the variable is set and non-empty. The value of the variable itself is not printed; the word replaces it. In the second half of the example, the title and its leading comma are added only when title exists.
Quoting and Word Splitting
A default value follows the usual quoting rules. Without quotes, a default made of several words is split into several words when the result is used as a command argument:
cat > d12.sh <<'EOF'
unset a
show() { echo "$# items"; for x in "$@"; do echo " [$x]"; done; }
show "${a:-two words}"
show ${a:-two words}
EOF
bash d12.sh
1 items
[two words]
2 items
[two]
[words]
Quote the whole expansion, as in "${a:-two words}", so the default stays together. Lesson 55 explains why quoting variables matters.
Defaults with set -u
The set -u option turns a read of an unset variable into an error. A default value is a safe way to read a variable that might not exist, because the expansion handles the missing case before the error can happen:
cat > d13.sh <<'EOF'
set -u
echo "default works with set -u: ${missing:-fallback}"
echo "plain read:"
echo "$missing"
echo "not reached"
EOF
bash d13.sh
default works with set -u: fallback
plain read:
d13.sh: line 4: missing: unbound variable
The expansion with :- succeeded, but the plain read stopped the script. Lessons 119 to 121 look at set -u and related strict-mode options.
Combining Defaults with Other Expansions
A default often feeds into another expansion in the same script. This example chooses a file name and then changes its extension with ${file%.txt}, which removes .txt from the end of the value (lessons 54 and 152 cover that operator):
cat > d15.sh <<'EOF'
file=${1:-report.txt}
echo "${file%.txt}.bak"
EOF
bash d15.sh
bash d15.sh data.txt
report.bak
data.bak
Without an argument the script used report.txt and printed report.bak. With data.txt it printed data.bak.