Default Values & Parameter Expansion Basics
In this page:
${var:-default}: Use a Fallback Without Changing var
${var:-default} expands to the value of var if it is set and non-empty, or to default otherwise, without ever modifying var itself. This is the most common way to give a variable a safe fallback value for use in a single expression.
Example: ${var:-default}: Use a Fallback Without Changing var
#!/bin/bash
unset username
echo "Hello, ${username:-Guest}!"
echo "username is still: [${username}]"
Login to try C/C++/Java/PHP code in the editor
${var:=default}: Use a Fallback and Assign It
${var:=default} behaves like :- but additionally assigns default into var when it was unset or empty, so subsequent references to var see the new value. This only works on plain variables, not on positional parameters like $1.
Example: ${var:=default}: Use a Fallback and Assign It
#!/bin/bash
unset config_path
echo "Config: ${config_path:=/etc/default/app.conf}"
echo "config_path is now: $config_path"
Login to try C/C++/Java/PHP code in the editor
${var:?message}: Require a Value
${var:?message} expands to var's value if it is set and non-empty; if not, it prints message to stderr and causes the script to exit with a non-zero status. This is a concise way to enforce that a required variable was actually provided.
Example: ${var:?message}: Require a Value
#!/bin/bash
api_key="abc123"
echo "Using API key: ${api_key:?ERROR: api_key must be set}"
Login to try C/C++/Java/PHP code in the editor
${var:+alt}: Only If Set
${var:+alt} expands to alt when var is set and non-empty, and to nothing when var is unset or empty -- the mirror image of :-. This is handy for conditionally including a flag or piece of text only when a variable has a real value.
Example: ${var:+alt}: Only If Set
#!/bin/bash
verbose="yes"
quiet=""
echo "Verbose flag: ${verbose:+--verbose}"
echo "Quiet flag: ${quiet:+--quiet}"
Login to try C/C++/Java/PHP code in the editor
- Confusing
:-(use default, don't assign) with:=(use default AND assign it back to the variable); they look similar but have very different side effects. - Forgetting the colon in
${var:-default}changes the meaning;${var-default}only triggers for a completely unset variable, while${var:-default}also triggers for a variable that is set but empty. - Using
${var:=default}on positional parameters like$1; Bash does not allow assigning to positional parameters this way and will raise an error.
${var:-default}expands todefaultifvaris unset or empty, without modifyingvaritself.${var:=default}does the same but also assignsdefaultback intovarfor later use.${var:?message}prints an error and exits the script ifvaris unset or empty -- useful for enforcing required inputs.${var:+alt}expands toaltonly ifvarIS set and non-empty (the inverse condition of:-).
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: