Bash Array

When you want to store multiple values in a single variable then the most appropriate data structure is array. There are two types of array in Bash-

  1. Homogeneous Array- Array having the same type of values are called homogeneous array.
  2. Heterogeneous Array- Array having different types of values are called heterogeneous array.

Syntax: How to declare an array in Bash

arrayvariable=(element1 element2 element3 ... elementn)

Here, each value in an array is separated by a space.

Example of declaring array in Bash

homo=(12 24 36 48)
hete=("Oreo" 8)

How to access array element in Bash?

Array in bash follows zero-based indexing which means the index position starts from zero. The first element in the array is assigned an index of zero. In order to access the elements of an array, enclose index position in square brackets. Follow the below syntax to understand it properly-

${arrayname[indexposition]}

Example of accessing array element in Bash

os=("Android" "iOS" "Window")
echo "First element of array: ${os[0]}"
echo "Second element of array: ${os[1]}"
echo "Third element of array: ${os[2]}"

Output of the above program

First element of array: Android
Second element of array: iOS
Third element of array: Window

Example: How to modify array element in Bash?

android=("Kitkat" "Lollipop" "Marshmallow")
echo "Array element before modification"
echo "First element of array: ${android[0]}"
echo "Second element of array: ${android[1]}"
echo "Third element of array: ${android[2]}"

echo "Array element after modification"
android[0]="Oreo"
android[1]="Nought"
android[2]="Pie"
echo "First element of array: ${android[0]}"
echo "Second element of array: ${android[1]}"
echo "Third element of array: ${android[2]}"

Output of the above program

Array element before modification
First element of array: Kitkat
Second element of array: Lollipop
Third element of array: Marshmallow
Array element after modification
First element of array: Oreo
Second element of array: Nought
Third element of array: Pie

How to get the length of array in Bash?

To get the number of elements in an array, use ${#arrayname[*]} statement. If you want to know the length of each array element, use ${#arrayname[indexvalue]} statement.

android=("Kitkat" "Lollipop" "Marshmallow")
echo "Total number of elements in array: ${#android[*]}"
echo "Length of first element: ${#android[0]}"
echo "Length of second element: ${#android[1]}"
echo "Length of third element: ${#android[2]}"

How to iterate array in Bash?

To loop through an array, follow the below syntax-

for element in ${arrayname[*]}
do
   echo $element
done

Example: How to loop through array in Bash

android=("Kitkat" "Lollipop" "Marshmallow")
for element in ${android[*]}
do
   echo $element
done

Output of the above program

Kitkat
Lollipop
Marshmallow