Bash 数组声明和附加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42023353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:42:40  来源:igfitidea点击:

Bash array declaration and appendation

arraysbashappenddeclare

提问by A.Jac

I'm trying to declare and append to an array in a bash script, after searching i resulted in this code.

我试图在 bash 脚本中声明并附加到一个数组,搜索后我得到了这段代码。

list=()
list+="string"

But when i echo this out it results in nothing. I have also tried appending to the array like this

但是当我回应这一点时,它什么也没有。我也试过像这样附加到数组

list[$[${#list[@]}+1]]="string"

I don't understand why this is not working, anyone have any suggestions?

我不明白为什么这不起作用,有人有什么建议吗?



EDIT:The problem is list is appended to inside a while loop.

编辑:问题是 list 附加到 while 循环内。

list=()

git ls-remote origin 'refs/heads/*' | while read sha ref; do
    list[${#list[@]}+1]="$ref"
done

declare -p list

see stackoverflow.com/q/16854280/1126841

见 stackoverflow.com/q/16854280/1126841

回答by Ali Okan Yüksel

You can append new string to your array like this:

您可以像这样将新字符串附加到数组中:

#!/bin/bash

mylist=("number one")

#append "number two" to array    
mylist=("${mylist[@]}" "number two")

# print each string in a loop
for mystr in "${mylist[@]}"; do echo "$mystr"; done

For more information you can check http://wiki.bash-hackers.org/syntax/arrays

有关更多信息,您可以查看http://wiki.bash-hackers.org/syntax/arrays

回答by Jdamian

Ali Okan Yüksel has written down an answer for the first method you mentioned about adding items in an array.

Ali Okan Yüksel 已经为您提到的关于在数组中添加项目的第一种方法写下了答案。

list+=( newitem  another_new_item ··· )

The right way of the second method you mentioned is:

您提到的第二种方法的正确方法是:

list[${#list[@]}]="string"

Assuming that a non-sparsearray has Nitems and because bash array indexes starts from 0, the last item in the array is N-1th. Therefore the next item must be added in the Nposition (${#list[@]}); not necessarily in N+1as you wrote.

假设一个非稀疏数组有N项并且因为 bash 数组索引从 开始0,数组中的最后一项是N-1th。因此必须在N位置 ( ${#list[@]}) 中添加下一项;不一定N+1像你写的那样。

Instead, if a sparsearray is used, it is very useful the bash parameter expansionwhich provides the indexes of the array:

相反,如果使用稀疏数组,则提供数组索引的bash 参数扩展非常有用:

${!list[@]}

For instance,

例如,

$ list[0]=3
$ list[12]=32
$ echo ${#list[@]}
2
$ echo ${!list[@]}
0 12