top of page

How to use Arrays in Bash Script

Bash Array – An array is a collection of elements. Unlike in many other programming languages, in bash, an array is not a collection of similar elements. Since bash does not discriminate string from a number, an array can contain a mix of strings and numbers.

How to Declare an Array in Bash?

Declaring an array in Bash is easy, but pay attention to the syntax. If you are used to programming in other languages, the code might look familiar, but there are subtle differences that are easy to miss.

To declare your array, follow these steps:

  1. Give your array a name

  2. Follow that variable name with an equal sign. The equal sign should not have any spaces around it

  3. Enclose the array in parentheses (not brackets like in JavaScript)

  4. Type your strings using quotes, but with no commas between them

Initialize 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.


arrayname=(element1 element2 elementN)


arr=("Apple" "Banana" "Mango" "Orange")
echo ${arr[@]}


Length of Array

To get length of an array in Bash, use the following syntax.




arr=("Apple" "Banana" "Mango" "Orange")
echo "Length of Array : $len"


Loop through Elements of Array

To loop through elements of array in Bash, use the expression ${arr[@]} to get all the elements and use For loop to loop through each one of these elements.


arr=("Apple" "Banana" "Mango" "Orange")
for element in "${arr[@]}";
    echo $element


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].


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



arr=("Apple" "Banana" "Mango" "Orange")
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}
echo ${arr[3]}


The Tech Platform

bottom of page