简体   繁体   English

在 Bash 中不指定索引的情况下向数组添加新元素

[英]Add a new element to an array without specifying the index in Bash

Is there a way to do something like PHPs $array[] = 'foo';有没有办法做一些像PHPs $array[] = 'foo'; in bash vs doing:在 bash 与做:

array[0]='foo'
array[1]='bar'

Yes there is:是的,有:

ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')

Bash Reference Manual : Bash 参考手册

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 变量或数组索引(请参阅数组)赋值的上下文中,“+=”运算符可用于附加或添加到变量的先前值。

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential.正如Dumb Guy指出的,重要的是要注意数组是否从零开始并且是连续的。 Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.由于您可以对非连续索引进行赋值和取消设置,因此${#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
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest

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

With an indexed array, you can to something like this:使用索引数组,您可以执行以下操作:

declare -a a=()
a+=('foo' 'bar')

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

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