# 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 commandsdone 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: applespearsoranges 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:

123

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 *.txtdo 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 \$idone

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

123

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