在 Bash 中不指定索引的情况下向数组添加新元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1951506/
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
Add a new element to an array without specifying the index in Bash
提问by Darryl Hein
Is there a way to do something like PHPs $array[] = 'foo';
in bash vs doing:
有没有办法$array[] = 'foo';
在 bash 中做类似 PHP 的事情vs 做:
array[0]='foo'
array[1]='bar'
回答by Etienne Dechamps
Yes there is:
就在这里:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=' operator can be used to append to or add to the variable's previous value.
在赋值语句为 shell 变量或数组索引(请参阅数组)赋值的上下文中,“+=”运算符可用于附加或添加到变量的先前值。
回答by Paused until further notice.
As Dumb Guypoints out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]}
is not always the next item at the end of the array.
正如Dumb Guy指出的,重要的是要注意数组是否从零开始并且是连续的。由于您可以分配和取消设置非连续索引${#array[@]}
并不总是数组末尾的下一项。
$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h
Here's how to get the last index:
以下是获取最后一个索引的方法:
$ end=(${!array[@]}) # put all the indices in an array
$ end=${end[@]: -1} # get the last one
$ echo $end
42
That illustrates how to get the last element of an array. You'll often see this:
这说明了如何获取数组的最后一个元素。你会经常看到这个:
$ echo ${array[${#array[@]} - 1]}
g
As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:
正如你所看到的,因为我们正在处理一个稀疏数组,这不是最后一个元素。不过,这适用于稀疏和连续数组:
$ echo ${array[@]: -1}
i
回答by ghostdog74
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
回答by Dumb Guy
If your array is always sequential and starts at 0, then you can do this:
如果您的数组始终是顺序的并且从 0 开始,那么您可以这样做:
array[${#array[@]}]='foo'
# gets the length of the array
${#array_name[@]}
If you inadvertently use spaces between the equal sign:
如果您不小心在等号之间使用了空格:
array[${#array[@]}] = 'foo'
Then you will receive an error similar to:
然后您将收到类似于以下内容的错误:
array_name[3]: command not found
回答by Grégory Roche
With an indexed array, you can to something like this:
使用索引数组,您可以执行以下操作:
declare -a a=()
a+=('foo' 'bar')