Datasheet

50
Phase 1
Working on the Command Line
To better understand the use of conditionals, consider the following code fragment:
if [ -s /tmp/tempstuff ]
then
echo "/tmp/tempstuff found; aborting!"
exit
fi
This fragment causes the script to exit if the file /tmp/tempstuff is present. The then key-
word marks the beginning of a series of lines that execute only if the conditional is true, and
fi (if backwards) marks the end of the if block. Such code might be useful if the script cre-
ates and then later deletes this file, since its presence indicates that a previous run of the script
didn’t succeed or is still working.
An alternative form for a conditional expression uses the test keyword rather than square
brackets around the conditional:
if test -s /tmp/tempstuff
You can also test a command’s return value by using the command as the condition:
if [ command ]
then
additional-commands
fi
In this example, the additional-commands will be run only if command completes success-
fully. If command returns an error code, the additional-commands won’t be run.
Conditional expressions are sometimes used in loops as well. Loops are structures that tell
the script to perform the same task repeatedly until some condition is met (or until some con-
dition is no longer met). For instance, Listing 1.5 shows a loop that plays all the .wav audio
files in a directory.
Listing 1.5: A Script That Executes a Command on Every Matching File in a Directory
#!/bin/bash
for d in `ls *.wav` ;
do play $d ;
done
The for loop as used here executes once for every item in the list generated by ls *.wav.
Each of those items (filenames) is assigned in turn to the $d variable and so is passed to the
play command.
Another type of loop is the while loop, which executes for as long as its condition is true.
The basic form of this loop type is like this:
83484.book Page 50 Monday, September 18, 2006 8:58 AM