用BASH中的循环填充数组

时间:2022-10-25 07:43:43

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

我想像这样在bash中自动填充一个数组:

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 个解决方案

#1


4  

You can simply:

你可以简单地说:

array=( $( seq 200 5 4800 ) )

and you have your array ready.

并准备好你的阵列了。

#2


7  

You can use += operator:

你可以使用+ =运算符:

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

#3


2  

Do it the way:

这样做是以bash的方式:

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

#4


0  

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

#1


4  

You can simply:

你可以简单地说:

array=( $( seq 200 5 4800 ) )

and you have your array ready.

并准备好你的阵列了。

#2


7  

You can use += operator:

你可以使用+ =运算符:

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

#3


2  

Do it the way:

这样做是以bash的方式:

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

#4


0  

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