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:
whileconditiondocommandsdone untilconditiondocommandsdone
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
doneThis 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
fiNote 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:
casestrinpattern_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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access