在 bash 中循环时更改数组值

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

change array value while looping in bash

arraysbash

提问by VextoR

The code

编码

SourceFolder[0]=""
SourceFolder[1]="inbound2"
SourceFolder[2]="inbound3"

for i in "${!SourceFolder[@]}"
do    
    if [ -z "${SourceFolder[$i]}"]; then
        ${SourceFolder[$i]} = "TEST"
    fi
done

${SourceFolder[$i]} = "TEST"- doesn't work

${SourceFolder[$i]} = "TEST"- 不起作用

it says

它说

=: command not found

=:找不到命令

How to change value in current loop index in an array?

如何更改数组中当前循环索引的值?

回答by UmNyobe

Because of the first space =is not interpreted as an assignment. There is a full explanation on So.

因为第一个空格=不被解释为赋值。So 上完整的解释

Btw ${SourceFolder[$i]}evaluate the array element, which is not what you want to do. For instance for the first one it is the empty string.

顺便说一句,${SourceFolder[$i]}评估数组元素,这不是您想要做的。例如,第一个它是空字符串。

Replaces with SourceFolder[$i]=

替换为 SourceFolder[$i]=

回答by xck

You must change indexnumber in the your array:

您必须更改数组中的索引号:

ARRAYNAME[indexnumber]=value

ok, you have array is:

好的,你的数组是:

array=(one two three)

you can add count to your script for initialize and change element for array indexnumber, example:

您可以在脚本中添加计数以初始化和更改数组索引号的元素,例如:

#!/bin/bash

count=0
array=(one two three)

for i in ${array[@]}
do
  echo "$i" 
  array[$count]="$i-indexnumber-is-$count"
  count=$((count + 1))
  echo $count
done

echo ${array[*]}

Result:

结果:

bash test-arr.sh 
one
1
two
2
three
3
one-indexnumber-is-0 two-indexnumber-is-1 three-indexnumber-is-2