【问题标题】:Bash assigning a variable to a command output which will be a list of multiple word strings [duplicate]Bash将变量分配给命令输出,该输出将是多个单词字符串的列表[重复]
【发布时间】:2022-01-06 05:26:13
【问题描述】:

这是我要运行的脚本

bRules=(`aws s3api get-bucket-lifecycle-configuration --bucket x |  jq '.Rules[]'.ID`)
echo "*** Total number of LifecycleRules ****  ${#bRules[@]}"
for rule in "${bRules[@]}"
do
    echo "Bucket: x, Rule: $rule"
done

实际输出

*** Total number of LifecycleRules ****  6
 Bucket: x, Rule: This
 Bucket: x, Rule: is
 Bucket: x, Rule: Rule-1
 Bucket: x, Rule: This
 Bucket: x, Rule: is
 Bucket: x, Rule: Rule-2

预期输出:

*** Total number of LifecycleRules ****  2
Bucket: x, Rule: This is Rule-1
Bucket: x, Rule: This is Rule-2

需要对我的代码 sn-p 进行哪些更改才能获得所需的输出?我有点迷失了解决这个问题。

【问题讨论】:

    标签: arrays string bash variable-assignment


    【解决方案1】:

    不要依赖命令替换和分词。请改用readarray(或mapfile,如果您愿意)并处理替换。

    您的循环也可以简化为单个printf

    readarray -t bRules < <(aws s3api get-bucket-lifecycle-configuration --bucket x | jq '.Rules[]'.ID)
    echo "*** Total number of LifecycleRules ****  ${#bRules[@]}"
    printf 'Bucket: x, Rule: %s\n' "${bRules[@]}"
    

    阅读Bash Manual

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2014-01-08
      • 2016-09-08
      • 2011-01-19
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多