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

Other Control Structures

This section describes other important Bourne shell and bash control structures.

The while and until Commands

The while statement is one way to create a loop. It has two forms:

while condition
do
   commands
done

until condition
do
   commands
done

In the while form, the commands are executed until the condition becomes false. In the until form, they are executed until the condition becomes true. Here is an example of while:

cat /etc/fstab | 
while read DEVICE MOUNT_DIR READONLY FS DUMMY1 DUMMY2 
do 
  fsck (if required) and mount the device 
done

This loop takes each line of /etc/fstab in turn (sent to it via cat) and performs an appropriate action for the corresponding device. The while loop will end when read (described later) returns a nonzero status, indicating an end-of-file.

Here is another very similar example, taken from a recent Linux system:

while read des fs type rest; do
  case "$fs" in
    /) break;;
    *)      ;;
  esac
done < /etc/fstab
if [ -e "$des" -a "$type" != "resiserfs" ]
then
  run fsck
fi

Note that the input to the while loop is provided via I/O redirection following the done statement.

The case Command

The case command is a way to perform a branching operation. Here is its syntax:

case str in 
   pattern_1)
     commands 
     ;; 
  
   pattern_2) 
     commands 
     ;; 
   ...
   pattern_n) 
     commands 
     ;; 
  
   *) 
     commands 
     ;; 
esac

The value in str is compared against each of the patterns. The corresponding commands are executed for the first match that is found. The double semicolons are used to end each section. Wildcards ...

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