【问题标题】:Best Practice : Print an array in a bash script最佳实践:在 bash 脚本中打印数组
【发布时间】:2019-08-04 14:06:17
【问题描述】:

我在脚本上运行了shellcheck,但在一个非常简单的方面遇到了错误 -

echo "已删除字段列表:${deleted[@]}"
^-----------^ SC2145:参数混合字符串和数组。使用 * 或单独的参数。

我正在尝试做如下类似的行为-

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

【问题讨论】:

    标签: arrays bash unix scripting


    【解决方案1】:

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

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

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

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

    $ printf '%s\n' "Hi there ${arr[*]}"
    Hi there a b c
    

    对于echo,这几乎无关紧要,因为您可能并不关心echo 是接收一个还是多个参数。

    【讨论】:

    • 谢谢!这澄清了我的疑问。
    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2016-02-02
    • 2013-07-17
    相关资源
    最近更新 更多