Linux Classes
Linux Training
* Linux Classes *

LINUX CLASSES - PROGRAMMING

How Does Shell Script Looping Work?

Shell scripts written in Bash can implement looping, or iteration, with the while, until, and for constructs. In each case, a block of code is executed repeatedly until a loop exit condition is satisfied. The script then continues on from that point.

The while Statement

In a while loop, the block of code between the do and done statements is executed so long as the conditional expression is true. Think of it as saying, "Execute while this condition remains true." Here's an example:

while [ "$*" != "" ]
do
  echo "Argument value is: $1"
  shift
done

This trivial example prints the value of each argument passed to the shell script. Translated to English, the while condition says to continue so long as the input argument string is not null. You could also code the while statement as

while [ -n "$*" ]

but I think the first method is much easier to read and understand.

You might think that this loop would continue to print the first argument ($1) forever and ever, since you don't expect the value of the $* variable (the list of arguments from the command line) to change during the course of running the script. You'd be right, except that I slipped the shift command into the body of the loop.

What shift does is discard the first argument and reassign all the $n variables--so the new $1 variable gets the value that used to be in $2, and so on. Accordingly, the value in $* gets shorter and shorter each time through the loop, and when it finally becomes null, the loop is done.

The until Statement

The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, "Execute until this condition becomes true."

Let's code the previous example using an until loop this time and making it a little fancier by adding a counter variable:

count=1
until [ "$*" = "" ]
do
  echo "Argument number $count : $1 "
  shift
  count=`expr $count + 1`
done

Again, you could have coded the until statement as

until [ -z "$*" ]

but I recommend not using the -n and -z operators because it's harder to remember what they do.

The only new concept here is the strange-looking line that increments the counter:

count=`expr $count + 1`

The expr command signals to the shell that we're about to perform a mathematical calculation instead of a string operation. And the doodads that look kind of like single quotation marks are not--they're the backtick (`) character, found to the left of the number 1 key on most keyboards. By enclosing an expression in backticks, you tell the shell to assign the result of a Linux command to a variable, instead of printing it to the screen.

Note: The spaces on either side of the plus sign are required.

The for Statement

The for statement is yet another way to implement a loop in a shell script. The general form of the for construct is shown here:

for item in list
do
  something useful with $item
done

Each time through the loop, the value of the item variable is assigned to the nth item in the list. When you've processed all the items in the list, the loop is done. Here's an example similar to the until and while loops you saw earlier in this section:

for item in "$*"
do
  echo "Argument value is: $item"
done

Previous Lesson: Shell Script Logic
Next Lesson: Shell Script Debugging

[ RETURN TO INDEX ]

Comments (most recent first)

Herbert mzamo     (13 May 2010, 07:22)
Very nice and clear examples for beginners, but for loop explanation is shallow and not quite clear for beginners
ND Stegs     (10 May 2010, 14:55)
@Dennis: I just realized this might also be useful for you.

while read LINE
do
echo $LINE
done < yourfile
ND Stegs     (10 May 2010, 14:54)
@Dennis: I use this construction all the time.
for ITEM in `cat yourfile`
do
echo $ITEM
done
Note that each item is separated by any whitespace, so multiple items on a line will be treated separately.
Dennis     (05 May 2010, 03:57)
how to imput arguments in loop from file?
Navpreet     (15 Apr 2010, 00:14)
Very nice examples for beginners
Bob Rankin     (12 Feb 2010, 12:39)
Good catch! Fixed now...
David G     (12 Feb 2010, 12:26)
Nice set of examples. Minor note, in the last for loop you have:
for $item in "$*"

it should read:
for item in "$*"

*Name:
Email:
Notify me about new comments on this page
Hide my email
*Text:
 

Ask Bob Rankin - Free Tech Support
<Send This Link to a Friend>         <Bookmark This Page>


Copyright © by Bob Rankin
All rights reserved - Redistribution is allowed only with permission.