How to loop over items from AWS CLI output?

aws ecs list-tasks --cluster dev-ec2s

this shows the list like this below, in this case three lines, but it can change.

"taskArns": [

then I made this script,

task id such as 408879277ab24490b1b911b119c81414 is set as environment variable and throw to next command.

task_id=(aws ecs list-tasks --cluster dev-ec2s |
jq '.taskArns[0] | split(\"/\")[-1]' |
awk '{print substr($0, 2, length($0)-2)}')
aws ecs describe-tasks --cluster dev-ec2-cls --tasks "$task_id",

It can work on first row.

However I want to do this for every row.

How can I do this?


  • You can alter your JQ command by looping over the items ([]), then use split() and [-1] to select the task id's:

    jq -r '.taskArns[] | split("/")[-1]'

    This gives us a list of the task id's:


    Afterwards you can iterate over the result using .. | while read task_id; do:

    jq -r '.taskArns[] | split("/")[-1]' "$(aws ecs list-tasks --cluster dev-ec2s )" \   
        |  while read task_id; do 
               aws ecs describe-tasks --cluster dev-ec2-cls --tasks "$task_id";