Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill an array with values in a for loop

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[@]}
like image 929
Marta Avatar asked Mar 23 '23 12:03

Marta


1 Answers

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
like image 102
konsolebox Avatar answered Apr 02 '23 01:04

konsolebox