在 BASH 中用循环填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17360089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill an array with a loop in BASH
提问by ayasha
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?
你能帮我么?
采纳答案by ayasha
You can simply:
您可以简单地:
array=( $( seq 200 5 4800 ) )
and you have your array ready.
你已经准备好了你的阵列。
回答by anubhava
You can use +=operator:
您可以使用+=运算符:
for i in $(seq 200 5 4800); do
array+=($i)
done
回答by Olivier Dulac
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) * 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

