Bash How to Add to Array

Bash How to Add to Array

If you want to add a new item to the end of the array without specifying an index use:

~]$ my_array=()
~]$ my_array+=("Arch")
~]$ echo ${my_array[@]}
Arch

In our previous article Bash How to Print Array, we have already seen the array creation, accessing the array elements and getting the count of array.

The array is created and can be verified as follows:

$ declare -p my_array
declare -a my_array=([0]="Arch")

Now we add another element to the my_array:

my_array+=("Debian")
declare -p my_array
declare -a my_array=([0]="Arch" [1]="Debian")

Using declare to check the BASH variables

Now in order to find out the number of elements within our array, you can use “#” to get the index count, The indexed elements count are as follows for 2 element array:

echo ${#my_array[@]}
2

To add the elements to the end of the array you can use this technique demonstrated as follows:

As your array is sequential list, To insert the element to the last index, This is done by getting the total count of elements and adding that as the index:

my_array[${#my_array[@]}]="Fedora"

Now the 3rd element “Fedora” is inserted to the end of array

echo ${my_array[@]}
Arch Debian Fedora

as you already understood that “${#my_array[@]}” gets the length of the array.

Using this technique you can append arrays and also assign them to a new array as demonstrated in the following example:

new_array=(${my_array[@]} "Ubuntu")
echo ${new_array[@]}
Arch Debian Fedora Ubuntu

This is how the elements inside the new array are stored:

declare -p new_array
declare -a new_array=([0]="Arch" [1]="Debian" [2]="Fedora" [3]="Ubuntu")

Leave a Comment