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


The continue Statement

The continue statement, like break, is used only inside for, while, and do-while loops. It skips over the rest of the loop body, causing the next cycle around the loop to begin immediately. Contrast this with break, which jumps out of the loop altogether. Here is an example:

# print names that don't contain the string "ignore"

# first, save the text of each line
{ names[NR] = $0 }

# print what we're interested in
END {
   for (x in names) {
       if (names[x] ~ /ignore/)
           continue
       print names[x]
   }
}

If one of the input records contains the string `ignore', this example skips the print statement for that record, and continues back to the first statement in the loop.

This is not a practical example of continue, since it would be just as easy to write the loop like this:

for (x in names)
  if (names[x] !~ /ignore/)
    print names[x]

The continue statement in a for loop directs awk to skip the rest of the body of the loop, and resume execution with the increment-expression of the for statement. The following program illustrates this fact:

awk 'BEGIN {
     for (x = 0; x <= 20; x++) {
         if (x == 5)
             continue
         printf ("%d ", x)
     }
     print ""
}'

This program prints all the numbers from 0 to 20, except for 5, for which the printf is skipped. Since the increment x++ is not skipped, x does not remain stuck at 5. Contrast the for loop above with the while loop:

awk 'BEGIN {
     x = 0
     while (x <= 20) {
         if (x == 5)
             continue
         printf ("%d ", x)
         x++
     }
     print ""
}'

This program loops forever once x gets to 5.

As described above, the continue statement has no meaning when used outside the body of a loop.


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