Home > Enterprise >  How to create multiple bash arrays in loop
How to create multiple bash arrays in loop

Time:01-19

I'm trying to create multiple arrays and add a variable to the array

rando=$(echo $((1   $RANDOM % 10)))
for num in $(seq 1 $rando)
do
        arr$num=()
        arr$num =$num
        echo "${arr$num[@]}"
done

I was expecting;

  • iterate through the loop a random amount of times, 1 - 10
  • create a new array for each iteration
  • add the "num" variable to the array
  • print all elements of the array

CodePudding user response:

Using a nameref:

for ((num=1;num<=5;num  ))
do
    declare -n arr="arr$num"                    # nameref

    arr=()
    arr ="$num"                                 # assigns value to index=0, ie, [0]
    arr[$num]=$((num   10))

    echo "############## num = $num"
    typeset -p "${!arr}"

    for i in "${!arr[@]}"
    do
        echo "${!arr}[$i] = ${arr[$i]}"
    done
done

This generates:

############## num = 1
declare -a arr1=([0]="1" [1]="11")
arr1[0] = 1
arr1[1] = 11
############## num = 2
declare -a arr2=([0]="2" [2]="12")
arr2[0] = 2
arr2[2] = 12
############## num = 3
declare -a arr3=([0]="3" [3]="13")
arr3[0] = 3
arr3[3] = 13
############## num = 4
declare -a arr4=([0]="4" [4]="14")
arr4[0] = 4
arr4[4] = 14
############## num = 5
declare -a arr5=([0]="5" [5]="15")
arr5[0] = 5
arr5[5] = 15
  •  Tags:  
  • bash
  • Related