next up previous
Next: The case statement Up: Conditional Statements Previous: Conditional Statements

The if statement

A typical example of the if statement is:
if bin/testprg
then
echo return from the testprg is true
else
echo return from the testprg is false
fi

Every UNIX command returns on exit a value, which the shell can use. This value is held in the read-only shell variable $?. The value 0 (zero) signifies success; anything other than 0 (zero) signifies failure. In our example, if testprg executes successfully, the return value is 0 and the line:
return from the testprg is true
is printed. In case the execution was not successful, the line
return from the testprg is false
is printed.

The if statement is often used with the test program stored in /usr/bin directory. The test program has many parameters enabling it to check whether strings are equal or different, if the file exists, and much more. The complete description is in UNIX in a nutshell book. Sometimes the shorthand $[$ $]$ for the test program is used.

Example: Test if the file test.sh exists:
if $[$ -f test.sh $]$
then
echo file exists
else
echo file not found
fi

Note the syntax of the test command: $[$ $-$f file $]$. The spaces after '$[$' and before '$]$' are necessary.

The general syntax of the if statement is:
if test
then
commands (if condition is true)
else
commands (if condition is false)
fi

then, else and fi are shell reserved words and as such are only recognized after a newline or ; (semicolon). The if construct must end with a fi statement.
if statements may be nested:
if ...
then ...
else if ...
...
fi
fi

The elif statement can be used as shorthand for an else if statement. For example:
if ...
then ...
elif ...
...
fi
fi


next up previous
Next: The case statement Up: Conditional Statements Previous: Conditional Statements
Instructional Support Group 2008-08-05