【发布时间】:2018-04-26 16:32:30
【问题描述】:
我有一个脚本正在查询 AWS 区域以获取指定的子网掩码。在 AWS 中,默认的 VPC CIDR 块是 172.31.0.0/16,因此我编写了一个 if/else 语句来将该输出通过管道传输到 /dev/null,然后将所有其他 CIDR 块写入一个文本文件。出于某种原因,172.31.0.0/16 块仍在写入文本文件中。
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 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",
目标是在文本文件中不包含任何"172.31.0.0/16", 范围。
【问题讨论】:
-
您正在测试
172.31.0.0/16,,但通过的实际值是"172.31.0.0/16",我认为这些双引号很重要,对吧? -
可能想使用
jq -r而不是脆弱的awk/sed/grep构造。 -
@JNevill,是的,我需要将输出用双引号括起来。
-
echo "..." > /dev/null是无操作的;你可以用:替换它。 -
除非您打算将
cidr_blocks.txt合并到一个更大的 JSON 文件中(在这种情况下,您应该稍微改变您的方法),我不明白您为什么需要引号(或逗号) .
标签: bash shell if-statement stdout