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. Less detail
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.

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.


mkdir tempdir && cp workfile tempdir

sshd || echo "sshd failed to start"
Less detail
You can use both forms together (with care) - they are processed left to right, and && must come first.
mkdir tempdir && cp workfile tempdir || \
 echo "Failed to create tempdir"
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.


if [ -r $myfile ]
   cat $myfile
   echo $myfile not readable

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.


for file in *.dat
    echo Processing $file
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)
(single file)
© Dartmouth College