Home > Software design >  How can I save my response into a list in BASH?
How can I save my response into a list in BASH?

Time:04-24

My first bash script.

myvar=$(aws ec2 describe-regions|jq '.Regions[] | {RegionName: .RegionName }')
echo "${myvar}"| jq -c '.| .RegionName'

Using the 2 commands above. I successfully got the the following result in terminal

"af-south-1"
"eu-north-1"
"ap-south-1"
"eu-west-3"
"eu-west-2"
"eu-west-1"
"ap-northeast-3"
"ap-northeast-2"
"me-south-1"
"ap-northeast-1"
"sa-east-1"
"ca-central-1"
"ap-east-1"
"ap-southeast-1"
"ap-southeast-2"
"eu-central-1"
"us-east-1"
"us-east-2"
"us-west-1"
"us-west-2"

How to save the answer into an array, and iterate it?

I thought about

awsRegionList =$(${myvar}| jq -c '.| .RegionName')
echo awsRegionList

But it finishes with an error.

CodePudding user response:

You could create a single jq command to save the output into an array. Afterwards you can iterate over it with a for loop:

#!/bin/bash

awsRegionList=$(aws ec2 describe-regions | jq -r -c '.Regions[] | .RegionName')

for region in ${awsRegionList[@]}; do
    echo $region
done;

Note, using -r will remove the quotes as well, so the output will be:

eu-north-1
ap-south-1
eu-west-3
eu-west-2
eu-west-1
ap-northeast-3
ap-northeast-2
ap-northeast-1
sa-east-1
ca-central-1
ap-southeast-1
ap-southeast-2
eu-central-1
us-east-1
us-east-2
us-west-1
us-west-2

CodePudding user response:

First of all you can simplify the jq query to process the EC2 output in one go.

#!/usr/bin/env bash

# Map the output of jq parsed EC2 response into the $regionList array
mapfile -d '' regionList < <(
  # Get EC2 response in JSON piped
  aws ec2 describe-regions |

  # Process JSON into a null-delimited stream
  jq --join-output '.Regions[] | .RegionName   "\u0000"'
)

# Iterates the list
for regionName in "${regionList[@]}"; do

  # Do stuff with $regionName
  printf 'Doing stuff with: %s\n' "$regionName"
done
  • Related