Initialise Array

To initialise array with elements in Bash, use assignment operator =, and enclose all the elements inside braces () separated by spaces in between them. We may also specify the index for each element in the array.

Syntax

The syntax to initialise an array with elements is

arrayname=(element1 element2 elementN)

The syntax to initialise an array with elements and their respective indices is

arrayname=([index1]=element1 [index2]=element2 [indexN]=elementN)
ADVERTISEMENT

Examples

Initialise Array with Elements

In this tutorial, we will initialise an array arr with three string values.

Example.sh

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

Output

apple banana cherry

Initialise Array with Elements and their Indices

In this tutorial, we will initialise an array arr with three string values and also the index for each of the element.

Example.sh

arr=([2]="apple" [3]="banana" [4]="cherry")
echo ${arr[2]}
echo ${arr[3]}

Output

apple
banana

Conclusion

In this Bash Tutorial, we have learnt how to initialise an array in Bash shell.