有没有办法做一些类似php $array[] = 'foo';In bash vs doing:
array[0]='foo'
array[1]='bar'
有没有办法做一些类似php $array[] = 'foo';In bash vs doing:
array[0]='foo'
array[1]='bar'
当前回答
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
其他回答
是的,有:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
Bash参考手册:
在赋值语句将值赋给shell变量或数组索引(请参阅数组)的上下文中,' += '操作符可用于附加或添加变量的前一个值。
另外:
当使用复合赋值将+=应用于数组变量时(参见下面的数组),变量的值不会被取消设置(就像使用=时一样),并且新值将被追加到数组中,从数组的最大下标大1开始(对于索引数组)
使用索引数组,你可以这样做:
declare -a a=()
a+=('foo' 'bar')
如果你的数组总是连续的,并且从0开始,那么你可以这样做:
array[${#array[@]}]='foo'
# gets the length of the array
${#array_name[@]}
如果你不小心在等号之间使用空格:
array[${#array[@]}] = 'foo'
然后你会收到一个类似这样的错误:
array_name[3]: command not found
正如Dumb Guy指出的,重要的是要注意数组是否从0开始并且是连续的。因为你可以给不连续的下标赋值和取消设置${#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
下面是获取最后一个索引的方法:
$ end=(${!array[@]}) # put all the indices in an array
$ end=${end[@]: -1} # get the last one
$ echo $end
42
这说明了如何获取数组的最后一个元素。你会经常看到:
$ echo ${array[${#array[@]} - 1]}
g
如你所见,因为我们处理的是一个稀疏数组,所以这不是最后一个元素。这对稀疏数组和连续数组都有效,不过:
$ echo ${array[@]: -1}
i
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest