Add Elements To An Existing Array Bash

Viewed 2179

I need to process some data in several steps.

I first create a list of managed policies in AWS and put that list into an array:

readarray -t managed_policies < <(aws iam list-attached-user-policies --user-name tdunphy  --output json --profile=company-nonprod | jq -r '.AttachedPolicies[].PolicyArn')

But then I need to add more information to that array later on in my script. My question is, can I use readarray to do this? Or do I just need to ammend the data to the list using the command such as:

managed_policies+=($(aws iam list-attached-group-policies --group-name grp-cloudops --profile=compnay-nonprod | jq -r '.AttachedPolicies[].PolicyArn'))
3 Answers

I suggest to use option -O to append to your array:

mapfile -t -O "${#managed_policies[@]}" managed_policies < <(aws ...)

You can also do this:

readarray -t managed_policies < <(aws ...)
readarray -t tmp < <(aws ...)
managed_policies+=("${tmp[@]}")

Assuming you could make the calls to aws immediately (and the example you give suggest you can, since both sets of arguments are hard-coded), you only need a single call to readarray. (The function is just some unnecessary refactoring.)

get_policies () {
  aws iam list-attached-user-policies --output json --profile company-nonprod "$@"
}

readarray -t managed_policies < <(
 { get_policies --user-name tdunphy
   get_policies --group-name grp-cloudops
 } | jq -r '.AttachedPolicies[].PolicyArn')

(Off-topic, but it's also possible you can omit the call to jq by using appropriate arguments to aws to adjust the output appropriately.)

Related