Skip main navigation

For Loops

control flow with for loop

What is a loop? A loop is a construct which allows you to repeatedly execute the same commands. We will be discussing three types of loops: for loops, while loops and until loops.

Let’s start by looking at for loops. The basic syntax for a for loop is:

for variable in ${list}
do
# Execute some commands
done

We can define a list like so:

my_list="item1 item2 item3"

As a simple example, let’s create a list of fruits and use a for loop to return each item from our list:

fruits="apples pears oranges"
for fruit in ${fruits}
do
echo ${fruit}
done

This will output:

apples
pears
oranges

We can also use a for loop to iterate over a series of numbers. In this example, we’ll process the numbers 1 – 3 using a sequence expression. Here, you’ll see the range is specified by a beginning number (1) and an ending number (3) separated by ‘..’. This indicates that we want the sequence of numbers from the beginning to the ending number inclusive i.e. 1, 2 and 3.

for n in {1..3}
do
echo ${n}
done

This will output:

1
2
3

A common use of for loops is to iterate over the contents of a directory. Here is an example of how to list all files in the current directory:

for file in *
do
echo ${file}
done

Here we use ‘*’ as a wildcard to ask for all files and directories. We could extend this to look text files:

for file in *.txt
do
echo ${file}
done

This would return only those files that have a .txt file extension.

Finally, we’ll introduce you to the for loop syntax that uses three expressions: an initial value, a terminal value and an increment/decrement. Notice here that the increment uses the ‘++’ notation which simply means add 1.

for (( i=1; i<=3; i++ ))
do
echo $i
done

This example returns the same output as our earlier number series.

1
2
3

Your task

Create a for loop which iterates from 1 to 5 in increments of 1. If the value is 2 return “fizz” otherwise, return “buzz”.

Please try to answer the questions yourself first and then compare the results with other learners. Finally, you can find solutions in the download area.
© Wellcome Sanger Institute
This article is from the free online

Bioinformatics for Biologists: An Introduction to Linux, Bash Scripting, and R

Created by
FutureLearn - Learning For Life