如何在bash中使用jq工具修改JSON对象并更新字段与数组?
问题原因
你收到的报错是因为.Aliases.Quantity本身是数字类型的值,不是数组或对象,你使用[$i]的索引语法去访问数字,触发了类型不匹配错误。
同时你原有脚本的执行顺序也有问题:你拉取配置后先直接调用了update-distribution提交未修改的配置,之后才尝试改配置,完全颠倒了操作顺序。
调整后的完整实现代码
filename=cf.json # 替换为你实际的CloudFront分发ID dist_id=<你的分发ID> # 替换为你要新增的域名 new_domain="your-new-domain.example.com" # 1. 拉取最新的分发配置到本地 rm -f $filename aws cloudfront get-distribution-config --id $dist_id \ --query 'DistributionConfig' --output json > $filename # 2. 获取ETag用于更新校验 etag=$(aws cloudfront get-distribution-config --id $dist_id | jq -r '.ETag') # 3. 用jq修改本地配置:Quantity加1,同时给Items数组追加新域名 jq --arg new "$new_domain" \ '.Aliases.Quantity += 1 | .Aliases.Items += [$new]' \ $filename > tmp.json && mv tmp.json $filename # 4. 提交修改后的配置 aws cloudfront update-distribution \ --distribution-config file://$filename --id $dist_id --if-match $etag > /dev/null
内容的提问来源于stack exchange,提问作者Jananath Banuka
相关产品推荐
相关产品推荐

