Shell

從 jq 特定行獲取輸出

  • August 5, 2022

命令:

create_subnet=$(aws ec2 create-subnet --vpc-id "$create_vpc" --cidr-block 10.0.1.0/24 | jq -r '.subnet[].subnetid')

輸出:

"subnet": {

   "availabilityzone": "us-west-1b",
   "availabilityzoneid": "usw1-az3",
   "availableipaddresscount": 251,
   "cidrblock": "10.0.1.0/24",
   "defaultforaz": false,
   "mappubliciponlaunch": false,
   "state": "available",
   "subnetid": "subnet-0745e1611cf09a69a",
   "vpcid": "vpc-07c1508663040cbf7",
   "ownerid": "232856593288",
   "assignipv6addressoncreation": false,
   "ipv6cidrblockassociationset": [],
   "subnetarn": "arn:aws:ec2:us-west-1:232856593288:subnet/subnet-0745e1611cf09a69a",
   "enabledns64": false,
   "ipv6native": false,
   "privatednsnameoptionsonlaunch": {
     "hostnametype": "ip-name",
     "enableresourcenamednsarecord": false,
     "enableresourcenamednsaaaarecord": false
   }
 }
}

我需要採取以下行:subnet-0745e1611cf09a69a 並將其儲存到變數create_subnet

當我使用 bash -xi 執行腳本時,出現以下錯誤:

++ jq -r '.subnet[].subnetid'
++ aws ec2 create-subnet --vpc-id vpc-09399bbc31c98efe7 --cidr-block 10.0.1.0/24
jq: error (at <stdin>:24): Cannot iterate over null (null)

也許我寫錯了語法或類似的東西?我的意思是這個 - jq -r ‘.subnet$$ $$.subnetid’

.subnet不是數組,所以[]不需要。

jq -r '.subnet.subnetid'

這對我有用。

引用自:https://serverfault.com/questions/1107470