bluethundr
bluethundr

Reputation: 1325

Add arbitrary number of AWS groups to an array in bash

I am writing a bash script that needs to do the following:

  1. Ask the user for the number of AWS groups to add to a user account.
  2. Take the names of the groups that the user enters and adds them to an array.

This is the code I have with some pseudocode for what I want to do:

echo "Enter the number of AWS groups you want to add the user to: "
read -r num_groups
counter=1
while [ $counter -le $num_groups ]
do
echo "Enter the name of a group to add to the user: "
read -r aws_group_name
***add the names of the groups to an array***
((counter++))
done

I don't know the number of groups that the user will specify ahead of time. Each AWS account could have a different number of groups with different group names.

How do I add the list of names that the user gives to an array?

Upvotes: 0

Views: 22

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

You can append to an array using the += operator in Bash. To avoid having to count the groups, you can just loop until the input is empty:

while read -rp 'Enter name of group to add: ' name; do
    [[ -z $name ]] && break
    names+=("$name")
done

and usage would look like this:

Enter name of group to add: name1
Enter name of group to add: name2
Enter name of group to add:

after which names contains this:

$ declare -p names
declare -a names=([0]="name1" [1]="name2")

Upvotes: 1

Related Questions