Append Element(s) to Array

To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis.

We can specify one or more elements in the parenthesis to append to the given array.

In this tutorial, we will learn the syntax to append element(s) to an array, and cover some examples.

Syntax

The syntax to append an element to an array is

arrayname+=(element)

The syntax to append more than one element to the array is

arrayname+=(element1 element2 elementN)

We can append one or more elements to the array in a single statement. Specify all the elements in the parenthesis just like how we initialize elements for an array.

ADVERTISEMENT

Example

Append an Element to an Array

In the following script, we initialise an array arr with three string values and then append an element "mango" to this array.

Example.sh

arr=("apple" "banana" "cherry")
arr+=("mango")
echo ${arr[@]}

Output

apple banana cherry mango

Append Multiple Elements to an Array

In the following script, we initialise an array arr with three string values and then append two elements "mango" and "grape" to this array.

Example.sh

arr=("apple" "banana" "cherry")
arr+=("mango" "grape")
echo ${arr[@]}

Output

apple banana cherry mango grape

Conclusion

In this Bash Tutorial, we have learnt how to access elements of an array using index in Bash shell.