Text-only | Table of Contents (frame/ no frame) |
(18) Flow control |
A list can also be a set of simple commands or pipelines separated by ";,&,&&,||,|&". For the compound commands which branch on the success or failure of some list, it is usually[
or[[
, but can be anything.
list && list
list || list
Example:
mkdir tempdir && cp workfile tempdir sshd || echo "sshd failed to start"
You can use both forms together (with care) - they are processed left to right, and && must come first.
Example:mkdir tempdir && cp workfile tempdir || \ echo "Failed to create tempdir"
if
list; then list ; elif list; then list; else list; fi
Example:
if [ -r $myfile ] then cat $myfile else echo $myfile not readable fi
while
list; do list; done
until
list; do list; done
until
form just negates the test.
for
identifier [ in words ]; do; list; done
Example:
for file in *.dat do echo Processing $file done
$?
can be used instead of some of the above.
Compound commands can be thought of as running in an implicit subshell. They
can have I/O redirection independant of the rest of the script. Setting of variables in a real subshell does not
leave them set in the parent script. Setting variables in implicit subshells varies in behaviour among shells.
Older sh
could not set variables in an implicit subshell and then use them later,
but current ksh
can do this (mostly).
Example: ex11 display, text
Reading a file line by line. The book by Randal Michael contains 12 example ways to read a file line by line,
which vary tremendously in efficiency. This example shows the simplest and fastest way.
flow-control.src last modified Mar 26, 2010 | Introduction | Table of Contents (frame/no frame) |
Printable (single file) |
© Dartmouth College |