Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

What does `set -u` break, and how do you deal with optional variables and empty arrays?

AdvancedConceptFunctions, exit codes, strict mode and traps
Answer

set -u fails on any reference to an unset variable, including optional environment variables and positional parameters that were not passed.

set -u
debug=${DEBUG:-0}          # default for optional vars
first=${1:-}               # optional argument
[[ -n ${AWS_PROFILE-} ]]   # test without failing

Bash before 4.4 also treated "${arr[@]}" on an empty array as unbound (arr[@]: unbound variable); workaround ${arr[@]+"${arr[@]}"}. Bash 4.4+ (all current distros) handles empty arrays correctly, but macOS's 3.2 does not.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps