9

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

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.