DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Choosing one of two options: the if statement

The simplest form of if statement is illustrated on lines 81 to 84:

   94	:	if [ $help = 'yes' ]
   95	:	then
   96	:	  _help
   97	:	  exit 1
   98	:	fi
The statement following if is evaluated. If it is true (that is, if it returns a value of 0), the body of the if statement (from then to fi) is carried out. If it is nonzero, the body of the if statement is skipped.

if has the following structure:

if condition
then
commands executed if condition succeeds
fi

An alternative structure is the following:

if condition
then
commands executed if condition succeeds
else
commands executed if condition does
not succeed
fi

The following structure is also valid:

if condition1
then
commands executed if condition1 succeeds
elif condition2
then
commands executed if condition2 succeeds
fi

condition is a command that returns an exit value: zero if successful or some other value if it failed. The if command carries out test, then executes the series of commands (from then to else or fi) if and only if test returned a value of ``0'' or TRUE. (fi is the command denoting the end of an if construct.)

If the if command contains an else portion, the commands between else and fi are only carried out if the test returns a result other than TRUE; that is, if the test statement fails.

If the if statement is followed by an elif, the elif statement is carried out if the condition tested by the previous if statement fails. An elif statement is otherwise identical with an if statement.

The following two lines of code have the same effect:

if [ $answer = 'y' ]

if test $answer = 'y'

If the test succeeds, indicating that the value of answer is ``y'', then the first set of commands is carried out. Otherwise, the else ... fi section of the script is executed.


Next topic: Different kinds of test
Previous topic: Making choices and testing input

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005