top of page
Writer's pictureThe Tech Platform

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.


Syntax:

arrayname=(element1 element2 elementN)


Code:

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

Output:






Length of Array

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


Syntax:

${#arrayname[@]}

Code:

arr=("Apple" "Banana" "Mango" "Orange")
len=${#arr[@]}
echo "Length of Array : $len"

Output:






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.


Code:

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

Output:








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

arrayname[index]

Code:

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

Output:







The Tech Platform

Recent Posts

See All

Comments


bottom of page