O'Reilly logo

Essential System Administration, 3rd Edition by Æleen Frisch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required