代码之家  ›  专栏  ›  技术社区  ›  Darryl Hein IrishChieftain

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

  •  632
  • Darryl Hein IrishChieftain  · 技术社区  · 16 年前

    $array[] = 'foo'; 在bash与doing中:

    array[0]='foo'
    array[1]='bar'
    
    5 回复  |  直到 6 年前
        1
  •  1693
  •   Etienne Dechamps    16 年前

    是的,有:

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

    Bash Reference Manual :

    在赋值语句将值赋值给shell变量或数组索引(请参见数组)的上下文中,+=运算符可用于追加或添加变量的前一个值。

        2
  •  81
  •   Dennis Williamson    16 年前

    笨蛋 指出,重要的是要注意数组是否从零开始并且是连续的。因为您可以指定和取消设置非连续索引 ${#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
    
        3
  •  53
  •   Zenexer    13 年前
    $ declare -a arr
    $ arr=("a")
    $ arr=("${arr[@]}" "new")
    $ echo ${arr[@]}
    a new
    $ arr=("${arr[@]}" "newest")
    $ echo ${arr[@]}
    a new newest
    
        4
  •  31
  •   jww avp    7 年前

    如果阵列始终是连续的,并且从0开始,则可以执行以下操作:

    array[${#array[@]}]='foo'
    
    # gets the length of the array
    ${#array_name[@]}
    

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

    然后,您将收到类似以下内容的错误:

    array_name[3]: command not found
    
        5
  •  6
  •   codeforester    9 年前

    使用索引数组,您可以创建如下内容:

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