最佳实践:在 bash 脚本中打印数组

Poo*_*ain 5 unix arrays bash scripting

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[@]}"
Run Code Online (Sandbox Code Playgroud)

Which is a better practice to print the elements in the array?

echo "List of fields deleted: ${deleted[@]}"
Run Code Online (Sandbox Code Playgroud)

OR

echo "List of fields deleted: "
 for deletedField in "${deleted[@]}"; do echo "${deletedField}"; done
Run Code Online (Sandbox Code Playgroud)

che*_*ner 8

@在较长的字符串中包含一个-indexed 数组可能会产生一些奇怪的结果:

$ arr=(a b c)
$ printf '%s\n' "Hi there ${arr[@]}"
Hi there a
b
c
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为引用的扩展${arr[@]}是一系列单独的单词,一次printf使用一个。第一个单词aHi there前缀结尾(就像数组后面的任何内容都将附加到c)。

当数组扩展是较大字符串的一部分时,您几乎肯定希望扩展是单个单词。

$ printf '%s\n' "Hi there ${arr[*]}"
Hi there a b c
Run Code Online (Sandbox Code Playgroud)

使用echo,它几乎不重要,因为您可能不关心echo是接收一个还是多个参数。