Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
HelloWorld Avatar asked Nov 07 '25 16:11

HelloWorld


1 Answers

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.

like image 139
jarmod Avatar answered Nov 09 '25 09:11

jarmod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!