bash 为bash中循环内的数组元素赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12466177/
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
Assign value to element of an array inside a loop in bash
提问by Sadiel
I would like to modify the value to an element of an array and I don't know the syntax to do it
我想将值修改为数组的一个元素,但我不知道这样做的语法
for i in `seq 0 8`;
do
if [ ${config[$i]} = "value1" ]
then config[$i] = "value2" #<- This line
fi
done
采纳答案by kojiro
Technically, the only thing broken there is the whitespace. Don't put spaces around your operators in shell syntax:
从技术上讲,唯一被破坏的是空白。不要在 shell 语法中的运算符周围放置空格:
config[$i]="value2"
However, there are lots of other little things you may want to think about. For example, if an element of configcan contain whitespace, the test can break. Use quotes or the [[test keyword to avoid that.
但是,您可能还需要考虑许多其他小事情。例如,如果 的元素config可以包含空格,则测试可能会中断。使用引号或[[test 关键字来避免这种情况。
… if [[ ${config[$i]} = "value1" ]]
then config[$i]="value2" …
seqis a nonstandard external executable. You'd be better off using the builtin iteration syntax. Furthermore, assuming the iteration happens over all the elements in config, you probably just want to do:
seq是一个非标准的外部可执行文件。最好使用内置迭代语法。此外,假设迭代发生在 中的所有元素上config,您可能只想执行以下操作:
for ((i=0; i<${#config[@]}; i++));
do
if [[ ${config[$i]} = "value1" ]]
then config[$i]="value2"
fi
done
回答by Stephane Rouberol
Remove the 2 extra spaces like this:
删除 2 个额外的空格,如下所示:
config[$i]="value2"

