简体   繁体   English

Bash:如何声明空数组,然后向其中添加变量

[英]Bash: How to declare empty array, and then add variables to it

I was hoping a kind person more intelligent than me could help me out here.我希望有一个比我更聪明的善良的人可以帮助我。

I am working on a Bash script, and in it there is a for loop that will go around an unknown/undefined number of times.我正在处理一个 Bash 脚本,其中有一个for循环,它将运行未知/未定义的次数。

Now, in this for loop, there will be a value assigned to a variable.现在,在这个for循环中,将为变量分配一个值。 Let's call this variabe: $var1我们称之为变量: $var1

Each time the loop goes (and I will never know how many times it goes), I would like to assign the value inside $var1 to an array, slowly building up the array as it goes.每次循环进行时(我永远不知道它进行了多少次),我想将$var1的值分配给一个数组,随着它的进行慢慢地构建该数组。 Let's call the array $arr让我们调用数组$arr

This is what I have so far:这是我到目前为止:

for i in $( seq 0 $unknown ); do
    ...
    some commands that will make $var1 change...
    ...

    arr=("${arr[@]}" "$var1")
done

However, when I want to echo or use the values in the array $arr , I get no results但是,当我想回显或使用数组$arr的值时,我没有得到任何结果

Perhaps someone will kindly help me in the right direction?也许有人会在正确的方向上帮助我?

I would really appreciate it so much.我真的很感激。

You declare and add to a bash array as follows:您可以按如下方式声明并添加到bash数组中:

declare -a  arr       # or arr=()
arr+=("item1")
arr+=("item2")

Simple as that.就那么简单。

After executing that code, the following assertions (among others) are true:执行该代码后,以下断言(以及其他)为真:

${arr[@]}  == item1 item2
${#arr[@]} == 2
${arr[1]}  == item2

In terms of the code you provided, you would use:就您提供的代码而言,您将使用:

declare -a arr
for i in $( seq 0 $unknown ); do
    ...
    some commands that will make $var1 change...
    ...

    arr+=("$var1")
done

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

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