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
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.
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 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.
Bash arrays are not "first class values" -- you can't pass them around like one "thing".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With