How to Append Values to Array in Bash (3 Methods)


Often you may want to append values to an array in Bash.

You can use the following methods to do so:

Method 1: Append One Value to Array

my_array+=('Pelicans')

This particular example appends the element ‘Pelicans’ to the end of the array named my_array.

Method 2: Append Multiple Values to Array

my_array+=('Pelicans' 'Hornets' 'Blazers')

This particular example appends three new elements to the end of the array named my_array.

Method 3: Append an Array to Array

my_array1+=(${my_array2[@]})

This particular example appends all elements from array2 to the end of the array named array1.

The following examples show how to use each of these methods in practice.

Example 1: Append One Value to Array in Bash

We can use the following syntax to create an array named my_array that contains the names of various basketball teams, then append a new element with the name ‘Pelicans’ to the end of the array, then view all elements in the updated array:

my_array=(Mavs Hawks Nets Spurs Warriors Celtics Kings)
my_array+=('Pelicans')

echo "${my_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash append one value to array

Notice that the new element ‘Pelicans’ has been appended to the existing array named my_array.

Note: We used the syntax echo “${my_array[@]}” to display all elements in the array.

Example 2: Append Multiple Values to Array in Bash

We can use the following syntax to create an array named my_array and then append multiple elements to the end of the array:

my_array=(Mavs Hawks Nets Spurs Warriors Celtics Kings)
my_array+=('Pelicans' 'Hornets' 'Blazers')

echo "${my_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash append multiple values to array

Notice that all three new team names have been appended to the existing array named my_array.

Example 3: Append an Array to Array in Bash

We can use the following syntax to create an array named array1, then append all elements from another array named array2 to it:

array1=(Mavs Hawks Nets Spurs)
array2=(Warriors Celtics Kings)

array1+=(${array2[@]})

echo "${array1[@]}"

The following screenshot shows how to use this syntax in practice:

Bash append array to another array

Notice that all elements from the array named array2 have been added to the array named array1.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Read Lines of File into Array
Bash: How to Echo All Values in an Array
Bash: How to Slice an Array

Leave a Reply