Table of Contents
AWK - AWK Loops
Loops are used to execute a set of actions in a repeated manner.
The loop execution continues as long as the loop condition is true.
For loops
A for statement performs some initialization action, then it checks the condition.
If the condition is true, it executes actions, thereafter it performs increment or decrement operation.
The loop execution continues as long as the condition is true.
awk 'BEGIN { for (i = 1; i <= 5; ++i) print i }'
returns:
1 2 3 4 5
While Loop
A while loop keeps executing the action until a particular logical condition evaluates to true.
AWK first checks the condition; if the condition is true, it executes the action.
This process repeats as long as the loop condition evaluates to true.
awk 'BEGIN {i = 1; while (i < 6) { print i; ++i } }'
returns:
1 2 3 4 5
Do-While Loop
A do-while loop is similar to the while loop, except that the test condition is evaluated at the end of the loop.
In a do-while loop, the action statement gets executed at least once even when the condition statement evaluates to false.
awk 'BEGIN {i = 1; do { print i; ++i } while (i < 6) }'
returns:
1 2 3 4 5
Break Statement
Break is used to end the loop execution.
awk 'BEGIN { sum = 0; for (i = 0; i < 20; ++i) { sum += i; if (sum > 50) break; else print "Sum =", sum } }'
returns:
Sum = 0 Sum = 1 Sum = 3 Sum = 6 Sum = 10 Sum = 15 Sum = 21 Sum = 28 Sum = 36 Sum = 45
Continue Statement
A continue statement is used inside a loop to skip to the next iteration of the loop.
It is useful when you wish to skip the processing of some data inside the loop.
awk 'BEGIN { for (i = 1; i <= 20; ++i) { if (i % 2 == 0) print i ; else continue } }'
returns:
2 4 6 8 10 12 14 16 18 20
Exit Statement
Exit is used to stop the execution of the script.
It accepts an integer as an argument which is the exit status code for AWK process.
If no argument is supplied, exit returns a zero.
awk 'BEGIN { sum = 0; for (i = 0; i < 20; ++i) { sum += i; if (sum > 50) exit(10); else print "Sum =", sum } }'
returns:
Sum = 0 Sum = 1 Sum = 3 Sum = 6 Sum = 10 Sum = 15 Sum = 21 Sum = 28 Sum = 36 Sum = 45
Now check the return status of the script:
echo $?
returns:
10