Best Practice : Print an array in a bash script
Including a @
-indexed array inside a longer string can make for some weird results:
$ arr=(a b c)$ printf '%s\n' "Hi there ${arr[@]}"Hi there abc
This happens because the quoted expansion of ${arr[@]}
is a series of separate words, which printf
will use one at a time. The first word a
ends up with Hi there
prepended to it (just as anything following the array would be appended to c
).
When the array expansion is part of a larger string, you almost certainly want the expansion to be a single word instead.
$ printf '%s\n' "Hi there ${arr[*]}"Hi there a b c
With echo
, it barely matters, as you probably don't care whether echo
is receiving one or multiple arguments.