Array Loops in Bash

In this article we'll show you the various methods of looping through arrays in Bash. Array loops are so common in programming that you'll almost always need to use them in any significant programming you do. To help with this, you should learn and understand the various types of arrays and how you'd loop over them, which is exactly what we present in this article.

Before we proceed with the main purpose of this tutorial/article, let's learn a bit more about programming with Bash shell, and then we'll show some common Bash programming constructs.

A Brief Introduction to the Bash Shell

Shell is a Unix term for the interactive user interface with operating systems. The shell is the layer of programming that understands and executes the commands a user enters. In some systems, the shell is called a command interpreter. Basically, whatever you can do with GUI OS tools on Linux, you can usually do the same thing with a shell.

Most Unix-like operating systems come with a shell such as the Bash shell, Bourne shell, C shell (csh), and KornShell. However, these shells do not always come preinstalled with popular Linux distributions such as Ubuntu, Cent OS, Kali, Fedora, etc. Although the popular Bash shell is shipped with most Linux distributions and OSX.

The Bash shell is an improved version of the old Bourne shell, which was one of the first Unix/Linux shells in general use by the user base. It had limited features compared with today's shells, and due to this most of the programming work was done almost entirely by external utilities.

Bash, which is a POSIX-compliant shell, simply means Bourne-again shell. It was originally created as a replacement for the Bourne shell and hence came with many enhancements not available in the old shells.

To find the type or version of Bash you're OS has installed just type the following command:

$ echo $BASH_VERSION
3.2.57(1)-release

Shell Scripting with Bash

A shell script is a file containing one or more commands that you would type on the command line. In a script, these commands are executed in series automatically, much like a C or Python program. Here are some examples of common commands:

  • cat: Display content in a file or combine two files together. The original name of the 'cat' command is 'concatenate'
  • ls: List files/folders in a directory
  • pwd: Display path of your current working directory
  • chmod: Modify or change permissions of a file
  • chown: Change the ownership of a file or a script program
  • mkdir: Create a directory
  • mv: Move a file or folder from one directory to another
  • rm: Remove (delete) a file or directory
  • cd: Change your current working directory
  • exit: Close or exit from a terminal

There are many more basic commands not mentioned here, which you can easily find information on given the extensive amount of documentation on the Internet. Although, learning the basic commands above will teach you much of what you need to know.

You might notice throughout this article that every first line of a shell script begins with a shebang or hash-bang. It is a special type of comment which tells the shell which program to use to execute the file. For shell scripts, this is the #!/bin/bash line.

Now that you've been exposed to some common Bash commands, it's time to understand how to use arrays and loops. And finally we'll show some real-world examples of how you can loop over arrays in Bash scripts.

Loops in Bash

"Loops", or "looping", is simply a construct in which you execute a particular event or sequence of commands until a specific condition is met, which is usually set by the programmer. We have three types of loops available to us in Bash programming:

  • while
  • for
  • until

While Loop

If you have ever programmed before in any language, you probably already know about looping and how you can use it to control the flow of a program or script in addition to the if, elif, and else. Looping allows you to iterate over a list or a group of values until a specific condition is met.

Below is the syntax of while loop:

while <list>
do
    <commands>
done

The condition within the while loop can be dependent on previously declared variables, depending on your needs. Let's assume we have written a program named count.sh. The counter program prints the numbers 0 through 10. So our counter program will 'loop' from 0 to 10 only.

#!/bin/bash

count=0
while [ $count -le 10 ]
do
    echo "$count"
    count=$(( $count + 1 ))
done

The condition here is $count -le 10, which will return a true value as long as the $count variable is less than or equal (-le) to 10. Every time this condition returns true, the commands between do and done are executed.

Until Loop

In addition to while, we can also use the until loop which is very similar to the while loop. The syntax of the until loop is the same as the while loop, however the main difference is that the condition is opposite to that of while. Here the loop commands are executed every time the condition fails, or returns false.

#!/bin/bash

count=0
until [ $count -gt 10 ]
do
    echo "$count"
    count=$(( $count + 1 ))
done

Here the loop is executed every time $count is not greater than (-gt) 10.

For loop

Syntactically the for loop is a bit different than the while or until loops. These types of loops handle incrementing the counter for us, whereas before we had to increment it on our own.

The syntax of the for loop in Bash is:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

#!/bin/bash

for (( n=1; n<=10; n++ ))
do
    echo "$n"
done

Within the loop condition we tell it which number to start the counter at (n=1), which number to end the counter at (n<=10), and how much to increment the counter by (n++).

Another way to use this loop is like this:

#!/bin/bash

for user in Kate Jake Patt
do
    echo "$user"
done

Here we execute the loop for every string instance, which in this case is "Kate", "Jake", and "Patt".

Arrays in Bash

In Bash, there are two types of arrays. There are the associative arrays and integer-indexed arrays. Elements in arrays are frequently referred to by their index number, which is the position in which they reside in the array. These index numbers are always integer numbers which start at 0.

Associative arrays are a bit newer, having arrived with the version of Bash 4.0.

Below is the syntax for declaring and using an integer-indexed array:

#!/bin/bash

array=( A B C D E F G )
echo "${array[0]}"
echo "${array[1]}"
echo "${array[2]}"
echo "${array[3]}"
echo "${array[4]}"
echo "${array[5]}"
echo "${array[6]}"

In this article we're going to focus on integer-indexed arrays for our array loops tutorial, so we'll skip covering associative arrays in Bash for now, but just know that it is good to be aware of their existence.

Looping over Arrays

Now that we have seen and understand the basic commands of the Bash shell as well as the basic concepts of loops and arrays in Bash, let's go ahead and see a useful script using the loops and arrays together.

In our simple example below we'll assume that you want to display a list of your website's registered users to the screen. The list of users is stored in the variable users, which you need to loop over to display them.

#!/bin/bash

users=(John Harry Jake Scott Philis)
for u in "${users[@]}"
do
    echo "$u is a registered user"
done

With this syntax, you will loop over the users array, with each name being temporarily stored in u. The [@] syntax tells the interpreter that this is an indexed array that we'll be iterating over.

There are quite a few ways we can use array loops in programming, so be sure not to limit yourself to what you see here. We've simply shown the most basic examples, which you can improve upon and alter to handle your use-case.

Last Updated: July 12th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms