Search code examples
arraysbashunixscriptingshellcheck

Best Practice : Print an array in a bash script


I ran shellcheck on my script and ran into an error on a very simple aspect -

echo "List of fields deleted: ${deleted[@]}"
^-----------^ SC2145: Argument mixes string and array. Use * or separate argument.

I am trying to do similar behavior as below-

declare -a  deleted
deleted = ("some.id.1" "some.id.22" "some.id.333")
echo "List of fields deleted: ${deleted[@]}"

Which is a better practice to print the elements in the array?

echo "List of fields deleted: ${deleted[@]}"

OR

echo "List of fields deleted: "
 for deletedField in "${deleted[@]}"; do echo "${deletedField}"; done

Solution

  • 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 a
    b
    c
    

    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.