Bash 阵列修改
示例
变化指数
初始化或更新数组中的特定元素
array[10]="elevenths element" # because it's starting with 0
附加
修改数组,如果未指定下标,则将元素添加到末尾。
array+=('fourth element' 'fifth element')用新的参数列表替换整个数组。
array=("${array[@]}" "fourth element" "fifth element")在开头添加元素:
array=("new element" "${array[@]}")插入
在给定的索引处插入一个元素:
arr=(a b c d)
# insert an element at index 2
i=2
arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
echo "${arr[2]}" #output: new删除
使用unset内置删除数组索引:
arr=(a b c)
echo "${arr[@]}" # outputs: a b c
echo "${!arr[@]}" # outputs: 0 1 2
unset -v 'arr[1]'
echo "${arr[@]}" # outputs: a c
echo "${!arr[@]}" # outputs: 0 2合并
array3=("${array1[@]}" "${array2[@]}")这也适用于稀疏数组。
重新索引数组
如果已从数组中删除元素,或者不确定数组中是否存在间隙,这将很有用。要重新创建没有间隙的索引:
array=("${array[@]}")