shell 数组里追加数值_将元素追加到bash中的数组

bd96500e110b49cbb3cd949968f18be7.png

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

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. 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).

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.

So:

#!/bin/bash

for ((i=0; i<5; ++i)); do

args+=($i)

echo "${args[@]}"

done

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值