unbound variable error with set -u on empty array expansion
0 reputation · 21 May 2020, 17:24 UTC
Goal
Determine the intended behavior for empty arrays under set -u when using default-value expansions, and identify a reliable pattern that preserves nounset safety without boilerplate.
Constraints and uncertainty
Bash 4.4 and later treat a zero-element array as unset for nounset purposes, so ${arr[@]} triggers unbound variable even when the array variable exists. The same default-value syntax that silences the error for scalars—${var:-default}—does not suppress it for arrays (${arr[@]:-default} still fails). Upstream discussions have not settled whether an empty array should count as “set,” and the behavior changed between Bash 4.3 and 4.4, creating a version-dependent footgun for low-traffic scripts that source shared libraries with optional configuration arrays.
Questions
- Is there a POSIX-compatible expansion form that prevents the unbound variable error for empty arrays without disabling
set -ulocally? - What is the recommended idiom for distinguishing “array declared but empty” from “array never declared” while keeping nounset active?