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


The if-else Statement

The if-else statement is awk's decision-making statement. It looks like this:

if (condition) then-body [else else-body]

The condition is an expression that controls what the rest of the statement will do. If condition is true, then-body is executed; otherwise, else-body is executed. The else part of the statement is optional. The condition is considered false if its value is zero or the null string, and true otherwise.

Here is an example:

if (x % 2 == 0)
    print "x is even"
else
    print "x is odd"

In this example, if the expression `x % 2 == 0' is true (that is, the value of x is evenly divisible by two), then the first print statement is executed, otherwise the second print statement is executed.

If the else appears on the same line as then-body, and then-body is not a compound statement (i.e. not surrounded by curly braces), then a semicolon must separate then-body from else. To illustrate this, let's rewrite the previous example:

if (x % 2 == 0) print "x is even"; else
        print "x is odd"

If you forget the `;', awk won't be able to interpret the statement, and you will get a syntax error.

We would not actually write this example this way, because a human reader might fail to see the else if it were not the first thing on its line.


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