简体   繁体   English

将元素附加到 bash 中的数组

[英]Append elements to an array in bash

I tried the += operator to append an array in bash but do not know why it did not work我尝试使用 += 运算符在 bash 中附加一个数组,但不知道为什么它不起作用

#!/bin/bash


i=0
args=()
while [ $i -lt 5 ]; do

    args+=("${i}")
    echo "${args}"
    let i=i+1

done

expected results预期成绩

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

actual results实际结果

0
0
0
0
0

Any help would be appreciated.任何帮助,将不胜感激。

It did work, but you're only echoing the first element of the array.它确实有效,但您只是在回显数组的第一个元素。 Use this instead:改用这个:

echo "${args[@]}"

Bash's syntax for arrays is confusing. Bash 的数组语法令人困惑。 Use ${args[@]} to get all the elements of the array.使用${args[@]}获取数组的所有元素。 Using ${args} is equivalent to ${args[0]} , which gets the first element (at index 0).使用${args}等效于${args[0]} ,它获取第一个元素(在索引 0 处)。

See ShellCheck : Expanding an array without an index only gives the first element.请参阅ShellCheck扩展没有索引的数组仅给出第一个元素。

Also btw you can simplify let i=i+1 to ((i++)) , but it's even simpler to use a C-style for loop.另外顺便说一句,您可以将let i=i+1简化为((i++)) ,但使用 C 风格的for循环更简单。 And also you don't need to define args before adding to it.而且您也不需要在添加之前定义args

So:所以:

#!/bin/bash
for ((i=0; i<5; ++i)); do
    args+=($i)
    echo "${args[@]}"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM