How to fill an array with values in a for loop

11,240

Solution 1

Perhaps you mean this?

val1=$1
val2=$2
for i in {1..10}; do
    array[i]=$(( val1 + val2 ))
    (( ++val1 ))
done    
echo "${array[@]}"

If you bash doesn't support {x..y}, use this format:

for (( i = 1; i <= 10; ++i )); do

Also simpler form of

    array[i]=$(( val1 + val2 ))
    (( ++val1 ))

Is

    (( array[i] = val1 + val2, ++val1 )) ## val1++ + val2 looks dirty

Solution 2

konsolebox's answer is right, but here are some alternatives:

val1=$1
val2=$2
for i in {0..9}; do
    (( array[i]=val1 + val2 + i ))
done
echo "${array[@]}"


val1=$1
val2=$2
for (( i=val1 + val2; i < val1 + val2 + 10; i++ )); do
    array+=("$i")
done
echo "${array[@]}"
Share:
11,240

Related videos on Youtube

Marta
Author by

Marta

Updated on September 14, 2022

Comments

  • Marta
    Marta over 1 year

    I have to submit a script which adds two values within an for loop and puts every result in an array. I put together a script (which is not working) but I cannot figure out how to get it started.

    #!/bin/sh
    
    val1=$1
    val2=$2
    for i in 10
        do
            ${array[i]}='expr $val1+$val2'
            $val1++
        done    
    echo ${array[@]}