Bash Arrays Array Modification

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Change Index

Initialize or update a particular element in the array

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

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[@]}")


Got any Bash Question?