我跑了shellcheck
在我的脚本上并在一个非常简单的方面遇到了错误 -
echo "List of fields deleted: ${deleted[@]}"
^-----------^ SC2145: Argument mixes string and array. Use * or separate argument.
我正在尝试做如下类似的行为-
declare -a deleted
deleted = ("some.id.1" "some.id.22" "some.id.333")
echo "List of fields deleted: ${deleted[@]}"
打印数组中的元素哪个更好?
echo "List of fields deleted: ${deleted[@]}"
或者
echo "List of fields deleted: "
for deletedField in "${deleted[@]}"; do echo "${deletedField}"; done
最佳答案
包括一个@
较长字符串中的 -indexed 数组可能会产生一些奇怪的结果:
$ arr=(a b c)
$ printf '%s\n' "Hi there ${arr[@]}"
Hi there a
b
c
发生这种情况是因为
${arr[@]}
的引用扩展是一系列独立的词,其中printf
将一次使用一个。第一个字a
以 Hi there
结束前置(就像数组后面的任何内容都将附加到 c
)。当数组扩展是较大字符串的一部分时,您几乎肯定希望扩展是单个单词。
$ printf '%s\n' "Hi there ${arr[*]}"
Hi there a b c
与
echo
,这几乎无关紧要,因为您可能不在乎 echo
正在接收一个或多个参数。
关于arrays - 最佳实践 : Print an array in a bash script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149641/