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 ?

SteeleDev
  • 169
  • 1
  • 3
  • 12
  • See [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29) for a brief discussion of why `for variable in $(anything)` is a bad idea, and [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) for a discussion of how to _correctly_ iterate over lines of input one at a time. – Charles Duffy Feb 22 '21 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?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) at [unix.se]). – Charles Duffy Feb 22 '21 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`). – Charles Duffy Feb 22 '21 at 20:04

1 Answers1

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    ....though that's not the best way to iterate over `aws ec2`'s output, as discussed in [Don't Read Lines With For](https://mywiki.wooledge.org/DontReadLinesWithFor). – Charles Duffy Feb 22 '21 at 20:00