我尝试使用将所有主机从 elbv2 LoadBalancer 规则获取到一个数组来扩展列表。 我尝试使用
查询规则内的现有主机TESTOUTPUT=$(aws elbv2 describe-rules --rule-arns arn:aws:elasticloadbalancing:ap-northeast-1:xxxx:listener-rule/app/k8s-ctrlroute-xxx/xxx/xxx --region ap-northeast-1 --no-cli-pager)
效果很好,我得到了主机的 JSON。不,我尝试将输出直接解析为数组
TESTOUTPUT=$(aws elbv2 describe-rules --rule-arns arn:aws:elasticloadbalancing:ap-northeast-1:xxxx:listener-rule/app/k8s-ctrlroute-xxx/xxx/xxx --region ap-northeast-1 --no-cli-pager | jq [.Rules[0].Conditions[0].Values[]])
结果是预期的主持人。看起来像
[ "host1.cloud", "host2.cloud", "host3.cloud" ]
但是如果我不尝试添加带有 TESTOUTPUT+="host4.cloud" 的条目,我会得到
[ "host1.cloud", "host2.cloud", "host3.cloud" ]host4.cloud
所以我假设预期的数组不是数组。但 jq 输出是数组输出的语法。 也许有人可以借我两只眼睛来对这个案例有不同的看法,以找出我的代码中有什么问题。
因为它仍然只是一个字符串,尽管如果您将它提供给 JSON 解析器,那么它会代表一个有效的 JSON 数组;但 Bash 不是其中之一。
如果您想获取 Bash 数组中的输出,请尝试
testoutput=($(aws elbv2 describe-rules \
--rule-arns arn:aws:elasticloadbalancing:ap-northeast-1:xxxx:listener-rule/app/k8s-ctrlroute-xxx/xxx/xxx \
--region ap-northeast-1 --no-cli-pager |
jq '[.Rules[0].Conditions[0].Values[]] | @sh'))
最重要的变化是
| @sh
装饰器添加到 jq
表达式另外,为了更好地衡量,请用单引号
jq
表达式;并添加反斜杠换行来理清冗长的命令行。