I’ve read some of the related questions on the subject but didn’t find the precise one I have in mind. I hope it’s not because it is too stupid.
In Bash 5 (5.2.15 if that matters), does it make any difference declaring an array like:
declare -a foo
compared with:
declare -a foo=()
I wonder if the first declaration does ensure the creation of an empty array, or only the second one guarantees that?
You may ask, what the point in initializing an empty array? Why not initializing it only when it’s needed storing a first element?
Well, I don’t know, maybe?
Then another question arises, would it be safe to initialize the array only when storing the first element with the append operator? Like:
bar+=('baz')
(bar here being not defined before this first element is appended)
it seems not to be a problem, even if option nounset is set, but doing so, am I assured 'baz' will always be the first element in the array? Is it safe to do that?
Also, in the case I’d need to change the default scope of the variable, I guess I couldn’t avoid using declare (or local), and it seems wrong to call declare or local every times I append an element (while it seems to work though).
Sorry if it’s a stupid question or is badly worded.
Have a nice day.
Addressing the
declare -a foovsdeclare -a foo=()(vsfoo=()) question ...The results are going to depend on what's in
fooprior to thedeclare -a.Findings:
foois undefined thendeclare -a foo,declare -a foo=()andfoo=()behave the samefoois predefined thendeclare -a foowill maintain the predefined value, whiledeclare -a foo=()andfoo=()will clear the contents offooIf you know with 100% certainty your variable (
fooin this case) is undefined then you're safe withdeclare -a fooordeclare -a foo=()orfoo=().If you're not sure about the contents of the variable (eg, it was exported by the parent process) then you're safer explicitly clearing the variable with
declare -a foo=()orfoo=().If you need the array to be empty then I'd suggest always explicitly defining the array as empty via
declare -a foo=()orfoo=().NOTES:
fooand then try to define as an associative array (declare -A foo)unset fooas this eliminates any unwanted leftover behavior from otherdeclareflags (eg,-x,-r, etc), and thendeclareand populate the variablefoo=(a b c); declare -A fooyou'll generate an error sincebashwon't convert an 'indexed' array to an associative array ... a good example whereunset fooshould be run before creating/populating (a new)foo