Bash Parameter Defaults
Parameter defaults supply a fallback value when a variable is unset or empty. The fallback appears in place of the missing value.
A fallback for a missing name
The name variable is unset. The :- form prints Guest instead, and the variable stays unset.
echo "Hello, ${name:-Guest}"
echo "Name is still: [${name}]"Empty is not unset without the colon
The empty variable holds an empty string. With the colon, the fallback wins. Without it, the empty value wins.
empty=""
echo "[${empty:-fallback}]"
echo "[${empty-fallback}]"Assign a default with :=
The city variable is unset. The := form prints Paris and stores it, so the next line prints Paris too.
echo "${city:=Paris}"
echo "$city"Demand a value with :?
The missing variable is unset. The :? form stops the script and prints an error.
echo "${missing:?a name is required}"Example
name="Ada"
echo "${name:+Hello again, $name}"
echo "Hello, ${name:-Guest}"
unset name
echo "[${name:+Hello again}]"
echo "Hello, ${name:-Guest}"Key points
- ${var:-default}: use default when var is unset or empty.
- ${var:=default}: assign default to var when it is unset or empty.
- ${var:?message}: stop with message when var is unset or empty.
- ${var:+alternate}: use alternate only when var is set and not empty.
- Colon matters: without it, an empty value counts as set.
- Default forms leave the variable unchanged, except := which assigns.
In this example, the name starts set to Ada. The :+ form prints a greeting because the name is set and not empty. The :- form then prints the name itself, since a set value beats the fallback. After unset removes the name, the :+ form prints nothing inside the brackets. The final :- form prints Guest as the fallback.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ${name:=Paris} do when name is unset?