Go to the first, previous, next, last section, table of contents.


The while Statement

In programming, a loop means a part of a program that can be executed two or more times in succession.

The while statement is the simplest looping statement in awk. It repeatedly executes a statement as long as a condition is true. It looks like this:

while (condition)
  body

Here body is a statement that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.

The first thing the while statement does is test condition. If condition is true, it executes the statement body. After body has been executed, condition is tested again, and if it is still true, body is executed again. This process repeats until condition is no longer true. If condition is initially false, the body of the loop is never executed, and awk continues with the statement following the loop.

This example prints the first three fields of each record, one per line.

awk '{ i = 1
       while (i <= 3) {
           print $i
           i++
       }
}' inventory-shipped

Here the body of the loop is a compound statement enclosed in braces, containing two statements.

The loop works like this: first, the value of i is set to one. Then, the while tests whether i is less than or equal to three. This is true when i equals one, so the i-th field is printed. Then the `i++' increments the value of i and the loop repeats. The loop terminates when i reaches four.

As you can see, a newline is not required between the condition and the body; but using one makes the program clearer unless the body is a compound statement or is very simple. The newline after the open-brace that begins the compound statement is not required either, but the program would be harder to read without it.


Go to the first, previous, next, last section, table of contents.