bash 如何在for循环中用值填充数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18698268/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:30:23  来源:igfitidea点击:

How to fill an array with values in a for loop

arrayslinuxbashshell

提问by Marta

I have to submit a script which adds two values within an for loop and puts every result in an array. I put together a script (which is not working) but I cannot figure out how to get it started.

我必须提交一个脚本,该脚本在 for 循环中添加两个值并将每个结果放入一个数组中。我整理了一个脚本(不起作用),但我不知道如何开始。

#!/bin/sh

val1=
val2=
for i in 10
    do
        ${array[i]}='expr $val1+$val2'
        $val1++
    done    
echo ${array[@]}

回答by konsolebox

Perhaps you mean this?

也许你是这个意思?

val1=
val2=
for i in {1..10}; do
    array[i]=$(( val1 + val2 ))
    (( ++val1 ))
done    
echo "${array[@]}"

If you bash doesn't support {x..y}, use this format:

如果 bash 不支持{x..y},请使用以下格式:

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

Also simpler form of

还有更简单的形式

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

Is

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

回答by Aleks-Daniel Jakimenko-A.

konsolebox's answeris right, but here are some alternatives:

konsolebox 的答案是正确的,但这里有一些替代方案:

val1=
val2=
for i in {0..9}; do
    (( array[i]=val1 + val2 + i ))
done
echo "${array[@]}"



val1=
val2=
for (( i=val1 + val2; i < val1 + val2 + 10; i++ )); do
    array+=("$i")
done
echo "${array[@]}"