You are on page 1of 16

Array Loops in Bash https://stackabuse.

com/array-loops-in-bash/

Array Loops in Bash


By  Scott Robinson (https://twitter.com/ScottWRobinson) •
4 Comments (/array-loops-in-bash/#disqus_thread)

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 signi�cant 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 programing 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
Privacy

1 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

(https://en.wikipedia.org/wiki/Bash_(Unix_shell)) shell, Bourne shell, C shell


(csh), and KornShell. However, these shells do not always come pre-installed
with popular Linux distributions such as Ubuntu, Cent OS, Kali, Fedora, etc.
Although the popular Bash shell is shipped with most of Linux distributions
and OSX.

The Bash shell is an improved version of the old Bourne shell, which was one
of the �rst Unix/Linux shell 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 �nd 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 �le 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:

Privacy

2 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

cat : Display content in a �le or combine two �les together. The original

name of the 'cat' command is 'concatenate'


ls : List �les/folders in a directory

pwd : Display path of your current working directory

chmod : Modify or change permissions of a �le

chown : Change the ownership of a �le or a script program

mkdir : Create a directory

mv : Move a �le or folder from one directory to another

rm : Remove (delete) a �le 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 �nd 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 �rst line of a shell script
begins with a shebang (https://en.wikipedia.org/wiki/Shebang_(Unix)) or
hash-bang. It is a special type of comment which tells the shell which
program to use to use to execute the �le. 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 �nally we'll show some real-
world examples of how you can loop over arrays in Bash scripts.

Privacy

3 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Loops in Bash
"Loops", or "looping", is simply a construct in which you execute a particular
event or sequence of commands until a speci�c 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 �ow 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 speci�c 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
Privacy

4 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

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.

Subscribe to our Newsletter


Get occassional tutorials, guides, and jobs in your inbox. No spam ever.
Unsubscribe at any time.

Enter your email...

Subscribe

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
Privacy

5 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

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:

#!/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++ ).
Privacy

6 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

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 array are a bit newer, having arrived with the version of Bash 4.0.

Privacy

7 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

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 array for our array
loops tutorial, so we'll skip covering associative arrays in Bash for now, but
just know that it is god 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 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
Privacy

8 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

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.

 unix (/tag/unix/), bash (/tag/bash/), shell (/tag/shell/)


 (https://twitter.com/share?text=Array%20Loops%20in%20Bash&
url=https://stackabuse.com/array-loops-in-bash/)
 (https://www.facebook.com/sharer/sharer.php?u=https://stackabuse.com
/array-loops-in-bash/)
 (https://www.linkedin.com/shareArticle?mini=true%26url=https:
//stackabuse.com/array-loops-in-bash/%26source=https://stackabuse.com)

(/author/scott/)
About Scott Robinson (/author/scott/)
 Twitter (https://twitter.com/ScottWRobinson)

Subscribe to our Newsletter


Get occassional tutorials, guides, and jobs in your inbox. No spam ever.
Privacy

9 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Unsubscribe at any time.

Enter your email...

Subscribe

 Previous Post (/encoding-and-decoding-base64-strings-in-node-js/)

Next Post  (/command-line-arguments-in-node-js/)

Ad

Follow Us
Privacy

10 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

 (https://twitter.com   (https://stackabuse.com
/StackAbuse) (https://www.facebook.com /rss/)
/stackabuse)

Data Visualization in Python

(https://gum.co/data-visualization-in-python)

(https://gum.co/data-visualization-in-python)
Understand your data better with visualizations! With over 275+ pages, you'll learn the ins
and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh,
and more.

Privacy

11 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Learn more (https://gum.co/data-visualization-in-python)

Newsletter

Subscribe to our newsletter! Get occassional tutorials, guides, and reviews in


your inbox.

Enter your email...

Subscribe

No spam ever. Unsubscribe at any time.

Ad

Want a remote job?


Privacy

12 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Backend/Fullstack Engineer
Bravado 23 days ago (https://hireremote.io/remote-job/3007-backend-fullstack-engineer-at-
bravado)

ruby (https://hireremote.io/remote-ruby-jobs) ruby-on-rails (https://hireremote.io

/remote-ruby-on-rails-jobs) full-stack (https://hireremote.io/remote-full-stack-jobs)

python (https://hireremote.io/remote-python-jobs)

Financial Systems Analyst - Remote


Dataiku 8 hours ago (https://hireremote.io/remote-job/3251-�nancial-systems-analyst-
remote-at-dataiku)

ar (https://hireremote.io/remote-ar-jobs) data science (https://hireremote.io/remote-

data-science-jobs) �nance (https://hireremote.io/remote-�nance-jobs)

Sr. Product Designer


SocialChorus 12 hours ago (https://hireremote.io/remote-job/3247-sr-product-designer-at-
socialchorus)

product design (https://hireremote.io/remote-product-design-jobs)

  More jobs (https://hireremote.io)

Jobs via HireRemote.io (https://hireremote.io)

Privacy

13 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Prepping for an interview?

(https://stackabu.se/daily-coding-problem)

Improve your skills by solving one coding problem every day

Get the solutions the next morning via email

Practice on actual problems asked by top companies, like:

     

   Daily Coding Problem (https://stackabu.se/daily-coding-problem)

Ad

Privacy

14 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Recent Posts

Matplotlib Scatter Plot - Tutorial and Examples (/matplotlib-scatterplot-tutorial-and-


examples/)

How to Iterate over Rows in a Pandas DataFrame (/how-to-iterate-over-rows-in-a-pandas-


dataframe/)

Privacy

15 of 16 10/22/20, 4:04 PM
Array Loops in Bash https://stackabuse.com/array-loops-in-bash/

Python: Check Index of an Item in a List (/python-check-index-of-an-item-in-a-list/)

Tags

ai (/tag/ai/) algorithms (/tag/algorithms/) amqp (/tag/amqp/)

angular (/tag/angular/) announcements (/tag/announcements/)

apache (/tag/apache/) apache commons (/tag/apache-commons/) api (/tag/api/)

arduino (/tag/arduino/) arti�cial intelligence (/tag/arti�cial-intelligence/)

Follow Us

 (https://twitter.com   (https://stackabuse.com
/StackAbuse) (https://www.facebook.com /rss/)
/stackabuse)

Copyright © 2020, Stack Abuse (https://stackabuse.com). All Rights Reserved.


Disclosure (/disclosure) • Privacy Policy (/privacy-policy) • Terms of Service (/terms-of-service)

Privacy

16 of 16 10/22/20, 4:04 PM

You might also like