How to populate an array with values ​​in a for loop

I need to send a script that adds two values ​​to a for loop and puts each result in an array. I have compiled a script (which does not work), but I cannot figure out how to run it.

#!/bin/sh val1=$1 val2=$2 for i in 10 do ${array[i]}='expr $val1+$val2' $val1++ done echo ${array[@]} 
+4
source share
2 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 do not support {x..y} , use this format:

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

Also simpler form

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

Is an

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

konsolebox's answer is right, but here are a few 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[@]}" 
+2
source

Source: https://habr.com/ru/post/1501290/


All Articles