Datasheet

Task 1.9: Write Basic Scripts
51
while [ condition ]
do
commands
done
The until loop is similar in form, but it continues execution for as long as its condition is
false—that is, until the condition becomes true.
Using Functions
A function is a part of a script that performs a specific sub-task and that can be called by name
from other parts of the script. Functions are defined by placing parentheses after the function
name and enclosing the lines that make up the function within curly braces:
myfn() {
commands
}
The keyword function may optionally precede the function name. In either event, the
function is called by name as if it were an ordinary internal or external command.
Functions are very useful in helping to create modular scripts. For instance, if your script
needs to perform half a dozen distinct computations, you might place each computation in a
function and then call them all in sequence. Listing 1.6 demonstrates the use of functions in
a simple program that copies a file but aborts with an error message if the target file already
exists. This script accepts a target and a destination filename and must pass those filenames to
the functions.
Listing 1.6: A Script Demonstrating the Use of Functions
#/bin/bash
doit() {
cp $1 $2
}
function check() {
if [ -s $2 ]
then
echo "Target file exists! Exiting!"
exit
fi
}
check $1 $2
doit $1 $2
83484.book Page 51 Monday, September 18, 2006 8:58 AM