Using the do while loop

The do while loop is similar to the while loop; but the difference is, even if the condition is true, at least once the action will be performed unlike the while loop.

The syntax is as follows:

do 
action 
while (condition) 

After the action or actions are performed, the condition is checked again. If the condition is true, then the action will be performed again; otherwise, the loop will be terminated.

The following is an example of using the do while loop:

    $ cat awk_script
    BEGIN {
      do {
        ++x
        print x
      } while ( x <= 4 )
    }
    $ awk -f awk_script
    1
    2
    3
    4
    5
  

In this example, x is incremented to 1 and the value of x is printed. Then, the condition is checked to see whether x is less than or equal to 4. If the condition is ...

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.