8

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?

4

4 回答 4

13

您可以使用+=运算符:

for i in $(seq 200 5 4800); do
    array+=($i)
done
于 2013-06-28T08:12:40.250 回答
6

您可以简单地:

array=( $( seq 200 5 4800 ) )

你已经准备好你的阵列了。

于 2013-06-28T08:15:52.753 回答
5

的方式来做:

array=( {200..4800..5} )
于 2013-06-28T11:13:45.493 回答
0

这些方法可能会导致内存(或行的最大长度)问题,所以这里有另一个:

# 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 
}

像这样使用:

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
于 2013-06-28T08:51:28.160 回答