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.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner