Introduction to Unix |
|
![]() |
![]() |
5.12. Control Constructs¶
To allow users to automate tasks using shell script programs, BASH provide some basic control constructs for expressing program logic.
5.12.1. if
¶
See also
if [ test expressiony ]; then
statements
fi
if [ test expressiony ]; then
statements
else
other statements
fi
if [ test expressiony ]; then
statements
elif [ another test ]; then
alternate statements
else
other statements
fi
5.12.2. case
¶
The case
construct allows for a multi-branch selection statement.
SYNOPSIS
case word in
"pat1")
commands1
;;
"pat2"|"pat3") # or operation
commands2
;;
*) # default case
commands3
;;
esac
5.12.3. for
loop¶
The for
loop is used to iterate over a set of items.
The set of items might be obtained by the shell listing files, by reading
lines from a file, or by running a command with command substitution.
SYNOPSIS
for name in set
do
commands
done
EXAMPLES
for file in *.txt # set is a list of file produced by the shell
do
grep pattern $file
done
for i in $(cat file)
do
echo $i | sed 's/goat/cat/g'
done
for i in $(jot 1 5)
do
touch file$i.txt
done
5.12.5. until
loop¶
The until
loop behaves opposed of the while
loop in terms of the
test to continue executing the loop.
SYNOPSIS
until test
do
commands
done