Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Elements To An Existing Array Bash

Tags:

arrays

bash

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'))
like image 669
bluethundr Avatar asked Oct 31 '18 20:10

bluethundr


People also ask

How do I add elements to an array in bash?

To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis. We can specify one or more elements in the parenthesis to append to the given array.

How do I modify an array in bash?

To update element of an array in Bash, access the element using array variable and index, and assign a new value to this element using assignment operator.

What is the syntax to add an element to a specific array index in Unix?

To add an element to specific index of an array use. Get all elements before Index position2 arr[0] and arr[1]; Add an element to the array; Get all elements with Index position2 to the last arr[2], arr[3], ....


2 Answers

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

mapfile -t -O "${#managed_policies[@]}" managed_policies < <(aws ...)
like image 128
Cyrus Avatar answered Oct 21 '22 11:10

Cyrus


You can also do this:

readarray -t managed_policies < <(aws ...)
readarray -t tmp < <(aws ...)
managed_policies+=("${tmp[@]}")
like image 28
mickp Avatar answered Oct 21 '22 10:10

mickp