Arrays in Bash

Ganbayar Gansukh
2 min readMar 11, 2021

When we manage servers and linux generally, we need to rely on bash script a lot. But mastering bash takes time and effort. At the end of the journey, it will reward you with the magic of bash.

Here is how to handle arrays in bash.

basket=(pen pencil eraser bluepen)

The elements inside an array is indexed, and its position is assigned during the assignment, so pen will be at the position zero and the bluepen will be the third item. If we print them:

echo ${basket[0]}
pen
echo ${basket[3]}
bluepen

Bash arrays are zero indexed just like any other programming languages, but don’t get confused if you use any other shells (Bourne, csh, tcsh, …) which starts at 1. But KSH(The Korn Shell) is the only exception which bash incorporates the features from it. Most developers favorite (as well as mine) shell is, ZSH. It takes the best of the Bourne shell and csh, therefore the array index starts at 1. This has confused me before.

Here is some wrap up for bash array:

• The first position of an array has an index of 0
• A value accessed in the form of `${array=[index]}`
• We can assign a value to any position using an index

Let’s append an another item to the list:

basket+=(ruler)

Now, if we print them:

echo ${basket[*]}pen pencil eraser bluepen ruler

We can also add item at specific index, which it will replace the current item at the index specified.

basket[1]=pencilSharpenerecho ${basket[*]}
pen pencilSharpener eraser bluepen ruler

As you can see, we can print all of the items in the array simply by array[*] which [*] itself in computer, interpreted as all . There is also another way to simply print all by array[@] as well, if you feel like use the latter way.

Iterating through array is also a simple, just like most of the programming language.

for value in ${basket[@]}; do echo "Item is: " $value; done;Item is:  pen
Item is: pencilSharpener
Item is: eraser
Item is: bluepen
Item is: ruler

As you can see, handling an array in bash is not that scary as it seems, and using bash script in your daily routine.

I hope this intro to bash array was helpful to you and I will be writing more about bash topics.

--

--

Ganbayar Gansukh

I’m a self-taught software developer, passionate about user experience with a background in marketing, ui/ux.