Browse topics

Parameter expansion

Version
5.3
Review
Draft

Summary#

Parameter expansion can supply a default, require a value, or extract part of a string inside a single shell word. For the default, assignment, error, and alternate-value forms, a colon makes an empty value count the same as an unset variable.

Syntax#

bash
"${value:-fallback}"    # Use the fallback if unset or empty
"${value-fallback}"     # Use the fallback only if unset
"${value:=fallback}"    # Assign and use the fallback if unset or empty
"${value:?message}"     # Diagnose unset or empty and exit a non-interactive shell
"${value:+alternate}"   # Use the alternate if set and nonempty
"${path##*/}"           # Remove the longest prefix that matches */
"${file%.*}"            # Remove the shortest suffix that matches .*
"${value:offset:len}"   # Take up to len characters from a zero-based offset

Example#

The script compares an unset setting with an explicitly empty one, then extracts a stem from a path containing a space.

bash
(
  unset region
  printf 'unset: <%s>\n' "${region:-local}"

  region=
  printf 'empty with colon: <%s>\n' "${region:-local}"
  printf 'empty without colon: <%s>\n' "${region-local}"

  file='reports/night shift.csv'
  name=${file##*/}
  printf 'stem: <%s>\n' "${name%.*}"
)

Expected output#

Text
unset: <local>
empty with colon: <local>
empty without colon: <>
stem: <night shift>

Common mistakes#

Use - when the caller is allowed to choose an empty value. Prefix removal uses # or ## and suffix removal uses % or %%. Doubling the operator selects the longest match. These operators take shell patterns. For a negative substring offset, put a space after the colon, as in ${value: -3}, to distinguish it from the default-value operator.

An unbound variable error comes from set -u, also written set -o nounset, when an expansion refers to an unset variable or positional parameter. Write ${value-} where an unset value is acceptable, or ${value:?message} to stop with your own message. Before Bash 4.4, set -u also reports this error for "${items[@]}" on an empty array.

Version applicability#

The forms shown here work in Bash 3.2. For the substring form on that version, give a nonnegative length or omit it.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0