Thursday, November 17, 2005

Control Flow: Loops

Millions recognize the Shaker hymn, "Simple Gifts" from Aaron Copeland's "Appalachian Spring."

The words begin


'Tis the gift to be simple,
'tis the gift to be free,
'tis the gift to come down where you ought to be,
And when we find ourselves in the place just right,
It will be in the valley of love and delight.


Open Source programmers around the world today, like modern-day Shakers , practice freedom and simplicity. (The Shakers also practiced celibacy, however theirs was voluntary.)

In honor of the Shakers, you should try out the Linux, command-line version of their hymn, which is even simpler:


yes "'Tis the gift to be simple"


Unfortunately, no one can sing that fast.

The shell lets us bring this down to a reasonable pace with a loop:


while true
do
echo "'Tis the gift to be simple"
sleep 3
done


As usual, you should try this out, both in a file and on the command line. Try also substituting the lyrics to the K&R hymn, "Hello, world".

Once you know loops are available, it's surprising how useful they can be. This next loop tells us when the file "MY_LONG_AWAITED_OUTPUT" appears.

while true
do
if test -e MY_LONG_AWAITED_OUPUT
then
printf 'DONE!!!\a\n'
break
fi
done


See if you can use a loop sometime today.

0 Comments:

Post a Comment

<< Home