Text-only Table of Contents (frame/ no frame)
(18) Flow control Previous Top Next

Flow Control and Compound Commands

A list in these descriptions is a simple command, or a pipeline. The value of the list is the value of the last simple command run in it. More detail

Conditional execution: if/else

list && list
Execute the first list. If true (success), execute the second one.
list || list
Execute the first list. If false (failure), execute the second one.

Example:

mkdir tempdir && cp workfile tempdir

sshd || echo "sshd failed to start"
More detail
if list; then list ; elif list; then list; else list; fi
Execute the first list, and if true (success), execute the "then" list, otherwise execute the "else" list. The "elif" and "else" lists are optional.

Example:

if [ -r $myfile ]
then
   cat $myfile
else
   echo $myfile not readable
fi

Looping: 'while' and 'for' loops

while list; do list; done
until list; do list; done
Execute the first list and if true (success), execute the second list. Repeat as long as the first list is true. The until form just negates the test.

Example: ex4 display, text

for identifier [ in words ]; do; list; done
Set identifier in turn to each word in words and execute the list. Omitting the "in words" clause implies using $@, i.e. the identifier is set in turn to each positional argument.

Example:

for file in *.dat
do
    echo Processing $file
done
As with most programming languages, there are often several ways to express the same action. Running a command and then explicitly examining $? 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.


Previous Top Next


flow-control.src  last modified Mar 26, 2010 Introduction Table of Contents
(frame/no frame)
Printable
(single file)
© Dartmouth College