簡體   English   中英

將 AWS CLI 結果存儲到 bash 變量

[英]Store AWS CLI result to bash variable

我有這個命令:aws ec2 describe-security-groups | jq '.SecurityGroups[]| "(.GroupId)"'

我希望將標准輸出存儲到 bash 中的變量中。

主要目標:對存儲在此變量中的每個元素運行 for 循環到 go。

所以我這樣做了:

#!/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 [options] [...] [parameters] 要查看幫助文本,您可以運行:

幫助

我的假設是結果的 var 應該以這種方式存儲它的元素:

“SG-01A”

“sg-0c2”

“SG-4BF”

但不確定我的假設是否正確。

您需要進行一些更改。 -r標志添加到jq調用以獲取原始 output (刪除輸出周圍的引號)並在循環中使用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 腳本。 這可能在其他環境中也可用。

這是一個簡單但強大的解決方案:

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

即使 a.GroupId 值中有空格,這也將起作用。 另請注意,不需要字符串插值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM