Sum values from loop in bash

Asked by At

i need count total number of aws instances in all region and I write this script:

#!/bin/bash
for region in $(aws ec2 describe-regions --query "Regions[*].[RegionName]" --output text); do
      aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]' --region $region --output text | wc -l
done

The output is like this:

...
0
0
0
48
0
0
0
...

Is there a way to get the total of these values?

1 Answers

1
Florian Schlag On Best Solutions

Try the following

#!/bin/bash
SUM=0
for region in $(aws ec2 describe-regions --query "Regions[*].[RegionName]" --output text); do
      I="$(aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]' --region $region --output text | wc -l)"
      let SUM=SUM+I
done

echo "$SUM"