LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Loop Through Array Values and Assign At The Same Time in Bash (https://www.linuxquestions.org/questions/linux-newbie-8/loop-through-array-values-and-assign-at-the-same-time-in-bash-4175637307/)

bluethundr 08-28-2018 10:39 AM

Loop Through Array Values and Assign At The Same Time in Bash
 
Hello,

I am allowing users of our AWS accounts to attach multiple security groups to an AWS instance with a bash script I'm writing.

These lines get the user to specify how many SG's they want to use:

Code:

printf "Enter number of security groups to add: "
  read -r sg_answer


while [ "$sg_startvalue" -le "$sg_answer" ]; do
      read -rp "Enter Security Group ID $sg_startvalue : " security_group && security_groups+=("$security_group")
      sg_startvalue=$((sg_startvalue+1))
    done


And these lines add the security groups to the instance:

Code:

for aws_sg in "${security_groups[@]}"; do
        printf "Adding %s to %s\\n" "$tag_instance_id" "$aws_sg"
        aws ec2 modify-instance-attribute --instance-id "$tag_instance_id" --groups "$aws_sg" --profile="$aws_key"
        sleep 5
      done

Problem is this AWS command (aws ec2 mofify-instance-attribute) needs to add ALL of the security groups at the same time. I won't know how many security groups the user is adding ahead of time.

If you run that command in a loop (as I'm doing here) each time that command runs it replaces the $aws_sg value that preceded it.

How do I gather the arbitrary number of aws_sg values into one line that I can use with aws ec2 modify-instance-attribute?

ondoho 08-28-2018 01:58 PM

i'm not sure i understand, but to literally answer "Loop Through Array Values and Assign At The Same Time in Bash":

Code:

for ((i=0;i<${#array[@]};i++)); do
    array[i]="somevalue"
done



All times are GMT -5. The time now is 06:43 AM.