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:
whilecondition
docommands
done untilcondition
docommands
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:
casestr
inpattern_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 ...
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.