The if Statement

In this section, we begin looking at Bourne shell control structures: programming features seldom used on the command line. The first construct we will consider is if, used for conditional command execution. Here is the simplest syntax of an if statement and a simple if example:

if condition 
then 
   commands 
fi
  
if test -x /sbin/sendmail ; then 
   /sbin/sendmail $SENDMAIL_OPTIONS
fi

The if command runs the commands in condition. If they return a true value (zero exit status), the commands are executed; on a false, nonzero status, the script jumps to the command after fi.

The preceding example uses the test command to check for the file /sbin/sendmail and starts the daemon if it’s present and executable. We’ll look at constructing conditions more closely a little later. For now, notice the placement of the then command. then must appear to the shell as a separate command, or you’ll get an error. So it must be on a new line after the if command, or it must be separated from the if command by a semicolon. The same rules hold true for the fi command that ends the if construct.

There are more complex forms of if:

strings /vmunix | grep Unix > /tmp/motd 
i=`head -1 /etc/motd | grep -c Unix` 
if [ $i -eq 0 ]  
then 
   cat /etc/motd >>/tmp/motd 
else 
   tail +2 /etc/motd >>/tmp/motd 
fi 
mv /tmp/motd /etc/motd

This example illustrates the if-then-else construct. It updates the Unix version string in the message-of-the-day file. First, it gets the current Unix version string out of the kernel file ...

Get Essential System Administration, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.