jeudi 26 avril 2018

Bash if/else statement is not piping output correctly

I have a script that is querying AWS regions for specified subnet masks. In AWS, the default VPC CIDR block is 172.31.0.0/16, so I wrote an if/else statement to pipe that output to /dev/null and then write all other CIDR blocks to a text file. For some reason, the 172.31.0.0/16 block is still being written to the text file.

Code:

#!/bin/bash

get_cidrs() {
for region in `aws ec2 describe-regions --output text | cut -f3`
do
    echo -e "\nGetting subnets in region:'$region'..."
    describe_cidr=`aws ec2 describe-vpcs --region $region | grep '\Block":' | awk 'NR%2==0' | sed 's/CidrBlock": "//g'`

    echo "$describe_cidr"
    if [[ "$describe_cidr"  == "172.31.0.0/16," ]]; then
        echo "$describe_cidr" > /dev/null 2>&1
    else
        echo "$describe_cidr" >> cidr_blocks.txt
    fi
done
}

get_cidrs

Output:

Getting subnets in region:'eu-central-1'...
                    "172.31.0.0/16",

Getting subnets in IX region:'us-east-1'...
                    "10.247.92.0/23",
                    "10.247.90.0/23",

Text file:

cat cidr_blocks.txt
"172.31.0.0/16",
"10.247.92.0/23",
"10.247.90.0/23",

The goal is to not have any of the "172.31.0.0/16", ranges in the text file.

Aucun commentaire:

Enregistrer un commentaire