Assign defaults and report missing values
How it works
${p:=word} sets p to the fallback when unset or empty; ${p=word} sets it only when unset. Both produce the resulting value. These forms can assign ordinary writable variables, not positional or special parameters. ${p:?message} rejects unset or empty p, while ${p?message} rejects only unset p. In a noninteractive shell a failed check prints a diagnostic to stderr and exits nonzero; an interactive shell does not exit for this expansion error. Use a clear message without secrets. The examples below keep the failing check in a separate child Bash process.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
Assign once
Expected stdout:
blueblueThe variable receives the fallback and keeps it.
Preserve an empty setting
color=printf '[%s]' "${color=blue}" "$color"printf '[%s]' "${color:=blue}" "$color"Expected stdout:
[][][blue][blue]Without the colon an assigned empty string is valid.
Required setting, isolated failure
bash -c 'project=demo; printf "%s\n" "${project:?Project required}"'bash -c 'project=; printf "%s\n" "${project:?Project required}"' 2>diagnostic.txtprintf 'status=%s' "$?"Expected stdout:
demostatus=127The child rejects the empty setting; stderr is saved to a practice file. The observed status is 127 in this Bash invocation; rely on nonzero, not on this exact number across environments.
Common mistakes
Unlike :-, := changes the variable. Do not use :? if empty is an acceptable setting. Do not assume a script will continue after a failed required-value expansion.
Practice
Use := to initialize an unset color to blue, then print color again. In a separate script use :? to require project and observe its failure when empty.
Next: Alternate-value expansions