bash - 在 bash 中的循环内为数组的元素赋值

标签 bash

我想修改数组元素的值,但我不知道执行此操作的语法

for i in `seq 0 8`;
do
    if [ ${config[$i]} = "value1" ]
        then config[$i] = "value2"    #<- This line
    fi
done

最佳答案

从技术上讲,唯一有问题的是空格。不要在 shell 语法中将空格放在运算符周围:

config[$i]="value2"

但是,您可能还需要考虑许多其他小事情。例如,如果 config 的元素可以包含空格,则测试可能会中断。使用引号或 [[ 测试关键字来避免这种情况。

… if [[ ${config[$i]} = "value1" ]]
    then config[$i]="value2" …

seq 是一个非标准的外部可执行文件。你最好使用内置的迭代语法。此外,假设迭代发生在 config 中的所有元素上,您可能只想做:

for ((i=0; i<${#config[@]}; i++));
do
    if [[ ${config[$i]} = "value1" ]]
        then config[$i]="value2"
    fi
done

关于bash - 在 bash 中的循环内为数组的元素赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466177/

相关文章:

linux - 查找文件,转换并存储在同一个子目录中

bash - 如何在 fish 中使用 bash 函数

bash - 在bash中获取文件名末尾的数字

bash - 如何构建 bash 代码以更轻松地跟踪条件?

linux - 如何列出$PATH?

node.js - 从 Node 脚本打开交互式 SSH session

bash - 将标准输入的副本从 bash 脚本本身重定向到文件

python - 表达式 awk,python 中的字符无效

bash - 使用 bash,我如何将标准错误传递给另一个进程?

bash - 检查 bash 中是否存在远程文件