Main index

Introducing UNIX and Linux


Introduction to shells

Overview
Why do we need a shell?
Shell syntax
      Types of shell command
      Simple commands
      Pipelines
      Grouping commands
      Exit status
      List commands
Arithmetic
      Operators and functions
Making decisions
      The 'test' statement
            Operators used by 'test'
      The 'if' statement
Loops
      'For' loops
      'While' and 'until' loops
Searching for files
      Arguments to 'find'
Formatted output
      Arguments to 'printf'
Passing information to scripts
      Scripts with arguments
      Parameter expansion
Summary
Exercises

The 'if' statement

For making simple decisions based on a command's exit status, || and && are fine, but if many commands are involved it may become quite difficult to read. For this reason, another syntax for checking the exit status of a command is provided, taking the form of an if statement. To illustrate this, recall the example used to introduce || and &&:

mycommand || echo Cannot run mycommand
mycommand && echo mycommand ran OK

This could be rewritten using if as follows:

if mycommand
then echo mycommand ran OK
else echo Cannot run mycommand
fi

Note that the line that starts with else is optional and that keyword fi denotes the end of the statement.

This mechanism is very similar to that used in Pascal or C. You may find it easier, or clearer, to use than || or &&. It should be stressed that an if statement fulfills exactly the same function as || and &&.

Worked example

Write a script to inform you whether or not you have used more than 100k of disk space.
Solution: Using du with option -s will give you a number that represents the number of kilobytes of storage you have used, and will also display the name of the directory for which it performed that calculation. You can use cut to extract the first field of that output, namely the number. Then test can check whether this number is greater than 100, returning an exit status of 0 if so, and if can check this exit status and run echo to display a message if it is indeed the case.

# Evaluate the number of kilobytes of storage used
KBYTES=$( du -s ~ | cut -f2 -d' ')

# Check the value of KBYTES ..
if   [ $KBYTES -gt 100 ]
# and display message if >100
then echo "You have used more than 100k"
# and display message if <=100
else echo "You have used less than 100k"
fi
Using || and &&, this could have been coded so:
KBYTES=$( du -s ~ | cut -f2 -d' ')
( [ $KBYTES -gt 100 ] &&
      echo "You have used more than 100k" ) ||
  [ $KBYTES -gt 100 ] ||
      echo "You have used less than 100k"

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck