DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Using awk

if statements

The if statement's generic syntax is as follows:

if (expression) statement1[ else statement2]

The expression acting as the conditional has no restrictions; it can include the relational operators <, <=, >, >=, ==, and !=; the regular expression matching operators ~ and !~ ; the logical operators ||, &&, and !; juxtaposition for concatenation; and parentheses for grouping.

In the if statement, the expression is first evaluated. If it is nonzero and non-null, statement1 is executed; otherwise statement2 is executed. The else part is optional.

A single statement can always be replaced by a statement list enclosed in braces. The statements in the statement list are terminated by newlines or semicolons.

The following is a rewrite of the maximum population program from ``Performing arithmetic'', using an if statement:

   BEGIN { minpop=1000; maxpop=0; mincountry=""; maxcountry="" }
          {    if (maxpop < $3) {
               maxpop = $3
               maxcountry = $1
          } else
          {    if (minpop > $3) {
                 minpop=$3
                 mincountry=$1
             }
          }
   }
   END  { print maxcountry, maxpop
          print mincountry, minpop }
The following output results:
   China 866
   Australia 14

Next topic: while statements
Previous topic: Control flow statements

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003