gpt4 book ai didi

arrays - 在 bash 中将元素追加到数组

转载 作者:行者123 更新时间:2023-12-03 03:51:01 25 4
gpt4 key购买 nike

我尝试使用 += 运算符在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com