Terminal · intermediate

Shell parameter expansion

Parameter expansion replaces forms beginning with $ with a parameter's value or a transformation such as a default, required-value check, length, or pattern removal.

Why it matters

It performs common validation and string operations without extra processes, while precise colon and quoting semantics prevent unset or empty values from being mishandled.

Mental model

How to reason about shell parameter expansion

Select a parameter, test its state if an operator requests it, produce a replacement string, then let the surrounding quoting context determine further expansion.

Analogy

It is a compact form with rules such as 'use this field, but substitute a fallback or reject the form when the field is missing.'

Examples

See the boundary, not just the happy path

Worked example · Default for unset or empty

port=${PORT:-8080}

The colon form chooses 8080 when PORT is unset or expands to an empty value; it does not assign the fallback to PORT.

Worked example · Require configuration

: "${API_URL:?API_URL must be set and non-empty}"

The expansion reports the supplied diagnostic and causes a non-interactive shell to exit when API_URL is unset or empty; : otherwise consumes the value.

Useful contrast · Colon changes empty-value handling

${MODE-default} versus ${MODE:-default}

Without the colon, only an unset parameter triggers the default; with the colon, an unset or empty parameter does.

Common mistakes

Misconceptions to remove early

Confusing :- with :=

${x:-value} substitutes a fallback without updating x, while ${x:=value} also assigns the chosen default where assignment is permitted.

Leaving an expansion unquoted

In contexts where the shell performs word splitting or filename expansion, an unquoted value can become a different number of arguments.

Quick check

Can you predict the result?

1. If NAME is set to an empty string, what does ${NAME:-guest} produce?
  • guest
  • An empty string
  • The literal text NAME
Answer: guest
2. What is the important difference between ${x-value} and ${x:-value}?
Answer: The colon form uses the fallback for both unset and empty x; the other uses it only when x is unset.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster