nounset and optional parameters
set -u (nounset) reports an error for many expansions of unset parameters and exits a noninteractive shell. An empty variable is set, and is not an unset-variable error. Use ${name-default} for an unset-only default and ${name:-default} for unset or empty; use ${name:?message} when a value is mandatory and nonempty. Check argument count before reading positional parameters, or choose an explicit optional default. Quoted $@ is safe when there are no positional arguments. Do not use blanket defaults to hide missing required inputs. These are scalar examples; array-specific behavior can depend on the Bash version. The required-value expansion also fails when the variable is assigned an empty string, whereas the unset-only default preserves emptiness. The diagnostic example checks that its error log was actually created and contains the expected text.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Unset versus empty
set -uunset BM_MODEprintf 'missing=[%s]\n' "${BM_MODE-dev}"BM_MODE=printf 'empty=[%s]\n' "$BM_MODE"printf 'fallback=[%s]\n' "${BM_MODE:-dev}" Expected stdout:
missing=[dev]empty=[]fallback=[dev]The default form chosen determines whether emptiness matters.
Optional positional values
set -ushow() { printf 'count=%s name=[%s]\n' "$#" "${1-guest}" for arg in "$@"; do printf '[%s]\n' "$arg"; done}showshow ''Expected stdout:
count=0 name=[guest]count=1 name=[][]No argument and a supplied empty argument remain distinguishable.
Required variable in a child
bash -uc 'unset BM_REQUIRED; printf "%s\n" "${BM_REQUIRED:?required}"' 2> error.logrc=$?[[ $rc != 0 && -f error.log ]] || exit 1grep -Fq 'required' error.log || exit 1printf 'diagnostic found\n'printf 'child=%s\n' "$rc" Expected stdout:
diagnostic foundchild=127The exact nonzero status is observed on Bash 5.2.37; portable logic should not depend on this particular number.
Common mistakes
Do not assume nounset rejects empty values. Do not read $1 under nounset before checking the number of arguments unless it is deliberately required.
Practice
Create a function with a required first argument and optional second argument. Test zero arguments, an empty first argument and an omitted second argument.
Next: ERR traps and inheritance