我尝试使用 +=
运算符在 bash 中附加数组,但不知道为什么它不起作用
#!/bin/bash
i=0
args=()
while [ $i -lt 5 ]; do
args+=("${i}")
echo "${args}"
let i=i+1
done
预期结果
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
实际结果
0
0
0
0
0
最佳答案
它确实有效,但您只是回显数组的第一个元素。改用这个:
echo "${args[@]}"
Bash 的数组语法令人困惑。使用 ${args[@]}
获取数组的所有元素。使用 ${args}
相当于 ${args[0]}
,它获取第一个元素(索引 0 处)。
参见ShellCheck : Expanding an array without an index only gives the first element.
顺便说一句,您还可以将 let i=i+1
简化为 ((i++))
,但使用 C 风格 for< 更简单
循环。而且您在添加之前不需要定义 args
。
所以:
#!/bin/bash
for ((i=0; i<5; ++i)); do
args+=($i)
echo "${args[@]}"
done
关于arrays - 在 bash 中将元素追加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55316852/