Array in bash scripting.

Array in bash scripting is the great way to enhance your bash scripting, so let’s dive further into it.

Array is used when you want to use your data in more structured manner, for example, if you have list of students and you want them to be stored then you can’t create variable for each student. Best way would be to create an array.

In other words, Arrays are used to store your data in the Indexed List.

So we have seen what’s Array in bash scripting. Let’s understand it better with an example.

In below array, all the names of the students are stored in the in the variable called “Listofstudents”

Listofstudents=("Mark" "John" "Chris" "Tom")

Rules for Declaring an Array.

  1. Name your Array, In our example above our array name is Listofstudents
  2. As all the variables it should be followed by =
  3. It should be enclosed in parentheses
  4. There shouldn’t be any commas in between.

If you want to call any student, you can do it as below.

${Listofstudents['3']}

Let’s run these two commands on your shell

# Listofstudents=("Mark" "John" "Chris" "Tom")
# echo ${Listofstudents['3']}

What output you got? Did you get Tom Instead of Chris? That’s because Array starts from number 0. Which means Mark is at 0, John is at 1, Chris is at 2 and lastly Tom at 3

Iterating over Array using for loop.

If you want to iterate on them, you will have to use the script as below.

#!/bin/bash
Listofstudents=("Mark" "John" "Chris" "Tom")
for i in ${Listofstudents[@]}
do echo "Hello $i"
done

Lastly, there are many ways you can iterate over an Array and you shouldn’t really limit your self to the For Loop. Have you looked at Seq Command in Linux ? Just look at it if you still It’s quite helpful as well.

Leave a Comment