[英]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 -我在我的脚本上运行了shellcheck
并在一个非常简单的方面遇到了错误 -
echo "List of fields deleted: ${deleted[@]}" echo "已删除字段列表:${deleted[@]}"
^-----------^ SC2145: Argument mixes string and array. ^-----------^ SC2145:参数混合字符串和数组。 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
Including a @
-indexed array inside a longer string can make for some weird results:在较长的字符串中包含@
-indexed 数组会产生一些奇怪的结果:
$ 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.发生这种情况是因为${arr[@]}
的引用扩展是一系列单独的单词, printf
将一次使用一个单词。 The first word a
ends up with Hi there
prepended to it (just as anything following the array would be appended to c
).第一个单词a
以Hi there
结尾(就像数组后面的任何内容都将附加到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.使用echo
,这几乎无关紧要,因为您可能不在乎echo
是接收一个还是多个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.