ayasha
ayasha

Reputation: 1251

Fill an array with a loop in BASH

I would like to fill an array automatically in bash like this one:

200 205 210 215 220 225 ... 4800

I tried with for like this:

for i in $(seq 200 5 4800);do
    array[$i-200]=$i;
done

Can you please help me?

Upvotes: 9

Views: 26306

Answers (4)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

Do it the way:

array=( {200..4800..5} )

Upvotes: 6

Olivier Dulac
Olivier Dulac

Reputation: 3791

You could have memory (or maximum length for a line) problems with those approaches, so here is another one:

# function that returns the value of the "array"
value () { # returns values of the virtual array for each index passed in parameter
   #you could add checks for non-integer, negative, etc
   while [ "$#" -gt 0 ]
   do
      #you could add checks for non-integer, negative, etc
      printf "$(( ($1 - 1) * 5 + 200 ))"
      shift
      [ "$#" -gt 0 ] && printf " "
   done 
}

Used like this:

the_prompt$ echo "5th value is : $( value 5 )"
5th value is :  220

the_prompt$ echo "6th and 9th values are : $( value 6 9 )"
6th and 9th values are :  225 240

Upvotes: 0

user80168
user80168

Reputation:

You can simply:

array=( $( seq 200 5 4800 ) )

and you have your array ready.

Upvotes: 6

anubhava
anubhava

Reputation: 785128

You can use += operator:

for i in $(seq 200 5 4800); do
    array+=($i)
done

Upvotes: 16

Related Questions