首页 文章

向数组添加新元素,而不在Bash中指定索引

提问于
浏览
593

有没有办法像bash做的那样做PHPs $array[] = 'foo'; 做:

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

5 回答

  • 40

    使用索引数组,您可以这样:

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

    如果您的数组始终是顺序的并且从0开始,则可以执行以下操作:

    array[${#array[@]}] = 'foo'

    ${#array_name[@]} 获取数组的长度

  • 1182
    $ declare -a arr
    $ arr=("a")
    $ arr=("${arr[@]}" "new")
    $ echo ${arr[@]}
    a new
    $ arr=("${arr[@]}" "newest")
    $ echo ${arr[@]}
    a new newest
    
  • 63

    就在这里:

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

    Bash Reference Manual

    在赋值语句为shell变量或数组索引赋值的上下文中(请参阅数组),可以使用'='运算符追加或添加到变量的先前值 .

  • 2

    正如 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
    

    以下是获取最后一个索引的方法:

    $ 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
    

相关问题