最佳实践:在 bash 脚本中打印数组 [英] Best Practice : Print an array in a bash script
问题描述
我在脚本上运行了 shellcheck
并在一个非常简单的方面遇到了错误 -
I ran shellcheck
on my script and ran into an error on a very simple aspect -
echo "删除的字段列表:${deleted[@]}"
^-----------^ SC2145:参数混合字符串和数组.使用 * 或单独的参数.
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[@]}"
或
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:
$ arr=(a b c)
$ printf '%s\n' "Hi there ${arr[@]}"
Hi there a
b
c
发生这种情况是因为 ${arr[@]}
的引用扩展是一系列 单独的 单词,printf
将使用一个一次.第一个单词 a
以 Hi there
结尾(就像数组后面的任何内容都将附加到 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
使用 echo
时,它几乎不重要,因为您可能不关心 echo
是接收一个还是多个参数.
With echo
, it barely matters, as you probably don't care whether echo
is receiving one or multiple arguments.
这篇关于最佳实践:在 bash 脚本中打印数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!