Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 847
Poorva Jain Avatar asked Mar 13 '19 19:03

Poorva Jain


People also ask

How do I print an entire array in Bash?

Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.

What is [@] in shell script?

This answer is not useful. Save this answer. Show activity on this post. $@ is basically use for refers all the command-line arguments of shell-script.

How do I echo an array in Bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.

Can you pass an array in Bash script?

Bash arrays are not "first class values" -- you can't pass them around like one "thing".


1 Answers

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.

like image 91
chepner Avatar answered Oct 12 '22 01:10

chepner