0xsegfault
0xsegfault

Reputation: 3161

Looping through array with a while comparison

I am trying to loop through and array and while incrementing a value.

Here is my code.

#!/bin/bash -e

# set -x

GASLIMIT=8000000
LIMIT=268435456000000 
VM_FAMILY_ARRAY=(t2.xlarge t2.2xlarge t3a.xlarge t3a.2xlarge a1.4xlarge a1.metal m4.xlarge m4.2xlarge m5.4xlarge  m5.8xlarge m5.12xlarge m5.16xlarge m5.24xlarge m5.metal)


for i in "${VM_FAMILY_ARRAY[@]}"
do
    while [ $GASLIMIT -le "$LIMIT" ]
        do 
            echo "$i""$GASLIMIT"
            GASLIMIT=$(($GASLIMIT*2))
        done

done

I would like script's output to look like this:

t2.xlarge8000000
<!--SNIP-->
t2.xlarge268435456000000
m5.metal8000000
<!-SNIP->
m5.metal268435456000000

What I am getting right now is just the first member of the VM_FAMILY array (t2.xlarge) with the script exiting once it has reached $LIMIT

t2.xlarge8000000
t2.xlarge16000000
<!--SNIP-->
t2.xlarge67108864000000
t2.xlarge134217728000000
t2.xlarge268435456000000

I would appreciate pointers on this

Upvotes: 0

Views: 27

Answers (1)

AlexisBRENON
AlexisBRENON

Reputation: 3099

Your GASLIMIT variable is not reset to its "base" value inside your for loop.

Hence, after your first for iteration, GASLIMIT is already greater than LIMIT and your while loop never run.

#! /usr/bin/env bash

set -eu

LIMIT=268435456000000 
VM_FAMILY_ARRAY=(t2.xlarge t2.2xlarge t3a.xlarge t3a.2xlarge a1.4xlarge a1.metal m4.xlarge m4.2xlarge m5.4xlarge  m5.8xlarge m5.12xlarge m5.16xlarge m5.24xlarge m5.metal)

for i in "${VM_FAMILY_ARRAY[@]}"
do
    GASLIMIT=8000000
    while [ $GASLIMIT -le "$LIMIT" ]
        do 
            echo "$i""$GASLIMIT"
            GASLIMIT=$(($GASLIMIT*2))
        done
done

Upvotes: 1

Related Questions