Loops – Bash Scripting Tutorial

Introduction

Bash loops are very useful. In this section of our Bash Scripting Tutorial we will look at the different loop formats available to us, as well as discuss when and why you might want to use each of them.

Loops allow us to take a series of commands and keep executing them until a particular situation is reached. They are useful for automating repetitive tasks.

There are 3 basic loop structures in Bash scripting that we will look at below. There are also some instructions we can use to control loop operation.

While

loops One of the

easiest loops to work with is while loops. They say that while an expression is true, it still executes these lines of code. They have

the following format: while [ <some test>

] do < commands> done

You’ will notice that similar to if the test instructions are placed in square brackets [ ].

In the following example we will print the numbers from 1 to 10

:

Let’s break it down:

Line

  • 4 – We will initialize the variable counter with its initial value.
  • Line 5 – While the proof is true (counter is less than or equal to 10) we will do the following commands.
  • Line 7 – We can place any command here we want. Echo is being used here, as it is an easy way to illustrate what is happening.
  • Line 8 – Using the double brackets we can increase the value of the counter by 1.
  • Line 9 – We are at the bottom of the loop, so go back to line 5 and test again. If the test is true, run the commands. If the test is false, continue to run any commands after doing so.

Up loops

The

until loop is quite similar to the while loop. The difference is that it will execute the commands inside it until the test becomes a reality.

until [ <some test> ] do < commands> done

As you can see from the example above, the syntax is almost exactly the same as the while loop (just replace while with until). We can also create a script that does exactly the same as the previous while example by simply changing the test accordingly.

So you may be asking, ‘Why bother having the two different types of loops?’ We don’t necessarily do it. The while loop would be able to handle all scenarios. Sometimes, however, it just makes it a little easier to read if we express it with up rather than while. Think about the following statement

: Leave the towel on the line until it is dry.

We could have said

: Leave the towel on the line as long as it is not dry.

Or:

Leave the towel

on the line while it is wet

.

But they just don’t seem as elegant and easy to understand. So, by having as much time as until we can choose the one that makes the most sense to us and, as a result, we end up with code that is easier for us to understand when we read it.

For

loops

The for loop is a little different than the previous two loops. What it does is say that for each of the items in a given list, perform the given set of commands. It has the following syntax.

for var in <list> do<commands> done The for loop will take each item in the list

(in order, one after the other), assign that item as the value of the var variable, execute the commands between do and done, and then return to the top, take the next item in the list, and repeat. The list

is defined as a series

of strings, separated by spaces.

Here’s a simple example to illustrate

:

Let’s break it down:

Line

  • 4 – Create a simple list that is a series of names
  • . Line 6: For

  • each of the items in the $names list, assign the item to the $name variable and perform the following commands. Line 8: Echo the name on the screen only to show that the mechanism works.
  • We can have as many commands here as we want.
  • Line 11: Echo another command to show that the bash script continued to run normally after all items in the list were processed.

Ranges

We can also process a series of numbers

  • Line 4 – It is important when specifying a range like this that there are no spaces present between the square brackets { }. If there are, then it will not look like a range but as a list of items.

When you specify

a range, you can specify any number you want for both the initial value and the final value. The first value can also be larger than the second, in which case it will count backwards.

You can also specify a value to increase or decrease each time. To do this, add another colon ( .. ) and the step-by-step value.

One of the most useful applications of for loops is in the processing of a set of files. For this we can use wildcards. Let’s say we want to convert a series of .html files to .php files.

Loop control: break and continue

Most of the time your loops go through in a smooth and orderly manner. Sometimes, however, we may need to intervene and slightly alter its functioning. There are two statements we can issue to do this.

Break

The break statement tells Bash to leave the loop immediately. It may be that there is a normal situation that should cause the loop to end, but there are also exceptional situations where it should also end. For example, maybe we are copying files, but if the free disk space is below a certain level, we should stop copying.

Continue

The continue statement tells Bash to stop executing this iteration of the loop and start the next iteration. Sometimes there are circumstances that prevent us from going further. For example, maybe we’re using the loop to process a series of files, but if we come across a file that we don’t have read permission for, we shouldn’t try to process it.

Select

The selection mechanism allows you to create a simple menu system. It has the following format:

select var in <list>

do<commands> done

When invoked, it will take all the items in the

list (similar to other loops, this is a set of items separated by spaces) and present them on the screen with a number before each item. After this a message will be printed that will allow the user to select a number. When they select a number and press enter the corresponding element will be assigned to the var variable and the commands between do and done will be executed. When finished, a message will be displayed again so that the user can select another option.

Some points to note:

  • No error checking is performed. If the user enters something other than a number or a number that does not correspond to an item, var becomes null (empty) If
  • the

  • user presses enter without entering any data, the list of options will be displayed again
  • .

  • The loop will end when an EOF signal is entered or the interrupt statement is issued
  • .

  • You can change the PS3 system variable to change the message displayed.

Here is a simple example to illustrate its use

:

Let’s break it down:

  • Line 4 – Set a variable with the list of characters and one last option that we can select to exit. Note that the elements are separated by a space.
  • Line 6: Change the value of the PS3 system variable so that the message is set to something a little more descriptive. (Default is #?)
  • Lines 10 – 13 – If the last option, ‘Exit’ is selected, exit the selection loop.
  • Line 14 – Print a message just to show that the mechanism has worked. You can have as many commands here as you want.
  • Line 17: Print a message only to show that the script has continued normally after the selection loop.

And now let’s run the

Bash:

Activity Summary

script

Now that we have a large collection of tools under our belt, we can tackle some more interesting problems

. Create a simple script that will print

  • the numbers 1 – 10 (each on a separate line) and whether they are even or odd
  • .

  • Write a Bash script that will take a single command-line argument (a directory) and print each entry in that directory. If the entry is a file, its size will be printed. If the entry is a directory, it will print how many items are in that directory.
  • Create a command-line version of the Mastermind game. Instead of colored marbles, you can use letters or numbers or get creative and find another way.
  • Create a command-line version of the Tic Tac Toe game. Do it so you can play against the computer.