将AWS CLI结果存储到bash变量

我有此命令: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帮助

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

“ sg-01a”

“ sg-0c2”

“ sg-4bf”

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

pengsijing 回答:将AWS CLI结果存储到bash变量

这是一个简单但强大的解决方案:

while read -r val ; do
    echo val="$val"
done < <(aws ec2 describe-security-groups | jq -r '.SecurityGroups[] | .GroupId')

即使.GroupId值中有空格,此操作也将起作用。还要注意,不需要字符串插值。

,

您需要进行一些更改。将-r标志添加到jq调用中以获取原始输出(这将删除输出周围的引号),并在循环中使用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

PS(如果您使用的是VS Code),那么我建议安装并使用shellcheck之类的扩展名来整理您的Shell脚本。这可能在其他环境中也可用。

本文链接:https://www.f2er.com/3123511.html

大家都在问