0

I am trying to execute this script as bash test.sh

#!/bin/bash
for region in "aws ec2 describe-regions --output text | cut -f4";
  do 
     echo -e "\nListing Instances in region:'$region'...";
      aws ec2 describe-instances --region $region;
done

But the only output that I get for $region is the print of the command. so it says "Listing Instances aws ec2 describe-regions .. "

How can I fix this ?

3
  • See BashPitfalls #1 for a brief discussion of why for variable in $(anything) is a bad idea, and BashFAQ #1 for a discussion of how to correctly iterate over lines of input one at a time. Commented Feb 22, 2021 at 20:00
  • (Also, echo -e is itself better avoided, as it's wildly nonportable (not just between shells, but even between runtime configurations when your shell is known to be bash); see Why is printf better than echo? at Unix & Linux). Commented Feb 22, 2021 at 20:01
  • (also, using a .sh extension on a bash script is not great practice; it implies that it's a sh script, but bash and sh are two different languages; also, executable scripts are executables, and executables on UNIX typically don't have extensions at all -- you run ls, not ls.elf; similarly, one runs pip, not pip.py). Commented Feb 22, 2021 at 20:04

1 Answer 1

1

You aren't executing a command; you are iterating over a sequence containing exactly one element, the strings aws ec2 ...

You need a command substitution to actually execute the command:

for region in $(aws ec2 describe-regions --output text | cut -f4); do
    echo -e ...
    aws ec2 describe-instances --region "$region"
done
Sign up to request clarification or add additional context in comments.

1 Comment

....though that's not the best way to iterate over aws ec2's output, as discussed in Don't Read Lines With For.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.