Array Modification

suggest change

Change Index

Initialize or update a particular element in the array

array[10]="elevenths element"    # because it's starting with 0


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 an element at a given index:

arr=(a b c d)
# insert an element at index 2
arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
echo "${arr[2]}" #output: new


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


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:


Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents