将元素追加到bash中的数组 [英] Append elements to an array in bash

查看:384
本文介绍了将元素追加到bash中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用+ =运算符在bash中追加一个数组,但不知道为什么它不起作用

I tried the += operator to append an array in bash but do not know why it did not work

#!/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

任何帮助将不胜感激.

推荐答案

它确实起作用,但是您仅在回显数组的第一个元素.改用它:

It did work, but you're only echoing the first element of the array. Use this instead:

echo "${args[@]}"

Bash数组的语法令人困惑.使用${args[@]}获取数组的所有元素.使用${args}等效于${args[0]},它获取第一个元素(索引为0).

Bash's syntax for arrays is confusing. Use ${args[@]} to get all the elements of the array. Using ${args} is equivalent to ${args[0]}, which gets the first element (at index 0).

请参见 ShellCheck :此外,您可以将let i=i+1简化为((i++)),但是使用C样式的for循环更为简单.同样,您无需在添加args之前对其进行定义.

Also btw you can simplify let i=i+1 to ((i++)), but it's even simpler to use a C-style for loop. And also you don't need to define args before adding to it.

所以:

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

这篇关于将元素追加到bash中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆