Access Elements of Array using Index

To access elements of array using index in Bash, use index notation on the array variable as array[index].

Syntax

The syntax to access element of an array at specific index is

</>
Copy
arrayname[index]

Index starts from zero and increments in steps of one for the subsequent elements in the array.

This notation is an expression, so while accessing the element, enclose the expression in ${} as disambiguation mechanism.

Example

In the following script, we initialise an array arr with three string values and access the elements of this array using index.

Example.sh

</>
Copy
arr=("apple" "banana" "cherry")
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}

Output

apple
banana
cherry

Conclusion

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