manpagez: man pages & more
info gawk
Home | html | info | man

File: gawk.info,  Node: If Statement,  Next: While Statement,  Up: Statements

7.4.1 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 does.  If the 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; otherwise, the condition is true.  Refer to the following:

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

   In this example, if the expression 'x % 2 == 0' is true (i.e., if 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' keyword appears on the same line as THEN-BODY
and THEN-BODY is not a compound statement (i.e., not surrounded by
braces), then a semicolon must separate THEN-BODY from the 'else'.  To
illustrate this, the previous example can be rewritten as:

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

If the ';' is left out, 'awk' can't interpret the statement and it
produces a syntax error.  Don't actually write programs this way,
because a human reader might fail to see the 'else' if it is not the
first thing on its line.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.