Jananath Banuka
Jananath Banuka

Reputation: 3953

Using the bash script how to check if aws cli generated output is empty or not?

I need to get the Internet Gateways which are NOT attached to any of the vpc networks in aws.

Here, this below command:

igws=(aws ec2 describe-internet-gateways --query 'InternetGateways[*]' --region $REGION

echo $igws

This produces the output as below:

  1. for an attached internet gateway the Attachments block is not empty
[
    {
        "Attachments": [
            {
                "State": "available",
                "VpcId": "vpc-2e83a147"
            }
        ],
        "InternetGatewayId": "igw-5a61f333",
        "OwnerId": "<some-id>",
        "Tags": []
    }
]
  1. for an detached internet gateway the Attachments block is empty
[
    {
        "Attachments": [],
        "InternetGatewayId": "igw-0c8abdc3cb147c04d",
        "OwnerId": "<some-id>",
        "Tags": [
            {
                "Key": "Name",
                "Value": "VPNTEST"
            }
        ]
    }
]

How can I check if the Attachment value is empty or not?

I used the below command but it is not working as it doesnt capture the detached ones:

if [ -z "$igws.Attachments[]" ]; then
do
 echo "empty"
else
 echo "not empty"
fi

can someone help me?

Upvotes: 1

Views: 793

Answers (2)

baozilaji
baozilaji

Reputation: 304

maybe you can try this:

echo $igws|tr -s '\n' ' '|tr -d ' '|tr -s ',' '\n'|grep "Attachments"|awk -F':' '{print $2}'

Upvotes: 1

tshiono
tshiono

Reputation: 22042

If jq is available, please try:

if [[ -z $(jq '.[].Attachments[]' <<< "$igws") ]]; then
    echo "empty"
else
    echo "not empty"
fi

Upvotes: 1

Related Questions