Change Index
Initialize or update a particular element in the array
array[10]="elevenths element" # because it's starting with 0
Append
Modify array, adding elements to the end if no subscript is specified.
array+=('fourth element' 'fifth element')
Replace the entire array with a new parameter list.
array=("${array[@]}" "fourth element" "fifth element")
Add an element at the beginning:
array=("new element" "${array[@]}")
Insert
Insert an element at a given index:
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
Delete
Delete array indexes using the unset
builtin:
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
Merge
array3=("${array1[@]}" "${array2[@]}")
This works for sparse arrays as well.
Re-indexing an array
This can be useful if elements have been removed from an array, or if you're unsure whether there are gaps in the array. To recreate the indices without gaps:
array=("${array[@]}")