将AWS CLI的结果存储到Bash变量中

3
我有这个命令:aws ec2 describe-security-groups | jq '.SecurityGroups[]| "(.GroupId)"'
我想将stdout存储到bash变量中。
主要目标是:运行for循环以遍历存储在此变量中的每个元素。
所以我做了这个:
#!/bin/bash

result=$(aws ec2 describe-security-groups | jq '.SecurityGroups[]| "\(.GroupId)"'))

for val in "${result[@]}"; do
    aws ec2 some command $result
done

看起来bash将我的变量内容解释为字符串,因为我的for循环内部的命令没有正确获取结果:

"sg-01a" "sg-0c2" "sg-4bf"

用法:aws [选项] <命令> [<参数>]。 要查看帮助文本,可以运行:

aws help

我的假设是,结果变量应该以这种方式存储其元素:

"sg-01a"

"sg-0c2"

"sg-4bf"

但我不确定我的假设是否正确。


4
您可以使用AWS CLI提供的查询参数进行操作。因此,以下命令将把安全组id列表存储在变量result中:result=$(aws ec2 describe-security-groups --output text --query 'SecurityGroups[*].GroupId')。要遍历列表,请使用:for val in $result; do echo $val ; done - krishna_mee2004
2个回答

4

您需要进行一些更改。在 jq 调用中添加 -r 标志以获得原始输出(从而删除输出周围的引号),并在循环中使用 val 而不是 result 。 例如:

#!/bin/bash

result=$(aws ec2 describe-security-groups | jq -r '.SecurityGroups[].GroupId')

for val in $result; do
    echo "Run: aws xyz $val"
done

如果你正在使用VS Code,那么我建议安装并使用类似于shellcheck这样的扩展程序来对你的shell脚本进行代码检查。这个工具在其他环境中也可能可用。


2
这里有一个简单而强大的解决方案:
while read -r val ; do
    echo val="$val"
done < <(aws ec2 describe-security-groups | jq -r '.SecurityGroups[] | .GroupId')

即使在.GroupId值中有空格,这也能正常工作。注意,不需要使用字符串插值。

1
两种解决方案都能满足需求,但我会选择 jarmod 的那个,因为在我的当前技能水平(初学者)下,那个看起来更易读。谢谢大家! - HelloWorld

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接