Thursday, September 1, 2022

[SOLVED] Iteratively add a string to a bash array

Issue

I have some code here that generates an ec2 instance ID as an output, I would like to store the instance IDs in an array, but they are being concatenated as strings instead of an array. Any help?

tasks=$(aws ecs list-tasks --cluster ${cluster} | jq --raw-output ' .taskArns[]')
declare -a instances

for task in ${tasks[@]};
    do
        container=$(aws ecs describe-tasks --task ${task} --cluster ${cluster} | jq -r '.tasks[].containerInstanceArn' | cut -d "/" -f3 )
        # Add the output of the next command to instances array
        instances+=$(aws ecs describe-container-instances --cluster ${cluster} --container-instances ${container} | jq --raw-output '.containerInstances[].ec2InstanceId')

done

echo "${instances[@]}" 

The above code prints one string with all instances concatenated... where am I going wrong?


Solution

To append an element to an array, parentheses are required:

declare -a instances

instances+=( "some element" )
instances+=( "$(date)" )

declare -p instances
# => declare -a instances=([0]="some element" [1]="Wed Aug 31 09:39:21 EDT 2022")

The spaces are not required but improve readability IMO.



Answered By - glenn jackman
Answer Checked By - Marilyn (WPSolving Volunteer)