HelloWorld
HelloWorld

Reputation: 97

Store AWS CLI result to bash variable

I have this command: aws ec2 describe-security-groups | jq '.SecurityGroups[]| "(.GroupId)"'

I want the stdout to be stored into a variable in bash.

Main goal: run a for loop to go over each element stored on this variable.

So I did this:

#!/bin/bash

result=$(aws ec2 describe-security-groups | jq '.SecurityGroups[]| "\(.GroupId)"'))

for val in "${result[@]}"; do
    aws ec2 some command $result
done

Looks like bash is interpreting my variable's content as a string because my command inside for is not quiet getting the result properly:

"sg-01a" "sg-0c2" "sg-4bf"

usage: aws [options] [ ...] [parameters] To see help text, you can run:

aws help

My assumption is that the result's var should have it's elements stored in this way:

"sg-01a"

"sg-0c2"

"sg-4bf"

But not sure if my assumption is correct.

Upvotes: 4

Views: 7071

Answers (2)

jarmod
jarmod

Reputation: 78803

You need to make a couple of changes. Add the -r flag to the jq call to get raw output (which removes the quotes around output) and use val in your loop instead of result. Example:

#!/bin/bash

result=$(aws ec2 describe-security-groups | jq -r '.SecurityGroups[].GroupId')

for val in $result; do
    echo "Run: aws xyz $val"
done

PS if you are using VS Code, then I recommend installing and using an extension such as shellcheck to lint your shell script. This is probably available in other environments too.

Upvotes: 5

peak
peak

Reputation: 116870

Here's a simple but robust solution:

while read -r val ; do
    echo val="$val"
done < <(aws ec2 describe-security-groups | jq -r '.SecurityGroups[] | .GroupId')

This will work even if there are spaces within a .GroupId value. Notice also that there is no need for string interpolation.

Upvotes: 2

Related Questions