What do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?
IntermediateConceptVariables, quoting and expansions
Answer
| Form | If var is unset or empty |
|---|---|
${var:-x} |
expands to x (var unchanged) |
${var:=x} |
assigns x to var and expands to it |
${var:+x} |
expands to x only if var is set and non-empty, else nothing |
${var:?msg} |
prints msg to stderr and exits a non-interactive shell |
Without the colon (${var-x}), only "unset" triggers, not "empty".
: "${ENVIRONMENT:?set ENVIRONMENT to dev, staging or prod}"
: "${RETRIES:=3}"
curl ${VERBOSE:+-v} -fsS "$url" # adds -v only when VERBOSE is set
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateHow do you strip prefixes and suffixes with parameter expansion?IntermediateHow do you do search-and-replace, substrings, length and case conversion without external tools?Intermediate