sections in this module City College of San Francisco - CS160B
Unix/Linux Shell Scripting
Module: Loops1
module list

Loop Basics

Note to C++/Java programmers

(Other students can continue with What is a loop?)

Programmers at every level think they know it all. And yes, you know what a loop is - or at least you'd better. But loops in the shell are quite different: Lets compare them

C++/JavaShell
use a conditional expression to control a while loopuse a Unix command that succeeds or fails to control a while loop
iterate through items using arrays and countersiterate through items using a list and an implicit or explicit shift to remove items from the list

If I've confused you, good. Start by forgetting how loops work in whatever language you use. Instead of trying to force the shell to do what you're used to, learn how the shell naturally controls loops. The resulting code will be shorter, easier to follow, and even faster.

What is a loop?

You've used loops before, whether you've ever programmed or not. Suppose you are moving, and your room is full of boxes. You can carry one box at a time, and your job is to carry the boxes to the moving truck. When all the boxes are moved, you get to eat lunch. You used a loop to accomplish the task. We could write the loop like this:

while there is a box in the room
pick up box
move to truck
done
eat lunch

We're going to take a few minutes and discuss this simple loop. First, some terminology:

In a while loop, the loop condition generates a positive or negative result, just like this one does. So that we can talk about shell commands, we will say the loop condition either succeeds or fails. In our case 'there is a box in the room' succeeds if there is a box in the room. If not, it fails.

The loop execution proceeds as follows:

  1. the loop condition is evaluated. If it fails, the loop stops, and you do the next thing following the done statement (eat lunch) Otherwise
  2. the loop body is executed:
  1. start again at 1.
If we have 3 boxes to move, this loop will result in the following actions:

Note that there is a dependency between the loop condition and the loop body. Specifically, something in the loop body must affect the loop condition! For us, moving a box to the truck decreases the number of boxes in the room so, eventually, there are no more boxes. If nothing in the loop body caused the loop condition to change, the loop would never stop, giving us an infinite loop. In our case, if we moved the box from one side of the room to the other, our loop would never stop, because we would never decrease the number of boxes in the room.

We have expressed this loop as a while loop. We accomplished this by finding a command that will give us a success or failure status that we can use to indicate the loop is finished. This particular task, however, can also be processed by the other type of loop - the for loop.

A for loop executes the loop body for each item in a list of items. The loop relies on an iteration variable, which, in our case, would be the current box we are carrying. To successfully write a for loop, we must be able to generate a list of the things we want to process. In our example, the list consists of the boxes we have to move. We will name them box1 box2 and box3 and our iteration variable currentbox. Our loop proceeds by assigning the next box in the list to currentbox each time through the list, and deleting that box from the list:

for currentbox in list-of-boxes  
move currentbox to truck
done

Remember, when the next box is assigned to currentbox, it is removed from the list-of-boxes. Before the loop starts, the list-of-boxes contains box1 box2 box3, and currentbox is empty. Then, our loop proceeds as follows:

iterationcurrentboxlist-of-boxesloop body results in
1box1box2 box3move currentbox to truck
2box2box3move currentbox to truck
3box3emptymove currentbox to truck
4 list is empty - exit the loop

The operation of removing a box from the list-of-boxes each iteration is reminiscent of a command we used with commandline arguments : shift

The loop continues until the list is empty. Note that the loop body here does not have anything to do with altering the loop exit condition! We could move the box around the room instead of to the truck and the loop would still stop!! The for loop is safer - it is guaranteed to stop because the list will eventually be exhausted!

If you can list the items you need to process in a loop, use a for loop. 
If you can't, use a while loop.

Here's an example of a for loop in the shell. Let's see if you can figure out what it does:

for file in *.txt
do
cat "$file"
done

You guessed it - it runs the cat program successively on each item in the current directory whose name ends in .txt

Preview question: Can you write a while loop to echo each command-line argument your shell script was given? For now, just write it in words as we did in our move boxes problem.

Prev This page was made entirely with free software on linux:  
Kompozer
and Openoffice.org    
Next

Copyright 2010 Greg Boyd - All Rights Reserved.

Document made with Kompozer