Previously we have writ of the fair usefulness of Loops, and the bounty which we may enjoy when we make our Computers perform them for us. ‘For’ loops we examined last; upon this page we shall consider their trusty cousin, ‘while’. Rather than a list of values to iterate, ‘while’ employs instead an expression, evaluating it over and over and over and while it is True continuing on evermore.

Similar to ‘for’, the incantation spans more than one Line, but its complexity is not overmuch. The first Line contains the keyword itself, then an expression encased with square Brackets. Then the ‘enter’ key be pressed, and ye shall be shewn the secondary shell prompt, the right-facing lance tip: ‘>’. Type then the single keyword, ‘do’, and press ‘enter’ once more. Now enter thy commands to be repeated. It is not required to indent these, though God-fearing people do. End each command by pressing ‘enter’ again, and when thy commands are concluded, add one last Line with the single keyword ‘done’. Id est:

ℜ> while [ 1 ] > do > ls -l file.txt > sleep 60 > done -rw-r--r-- 1 ulrick admyn 0 Dec 15 21:09 file.txt -rw-r--r-- 1 ulrick admyn 128 Dec 15 21:10 file.txt <ctrl-c> > _
An Antelope

This example shows a simple but worthwhile application of the device: an Infinite Loop. To halt it, ye must enter the canonical command canceller, ‘ctrl c’, control see. You wouldn’t put this in a scripte, but ’tis a nimble instrument for temporary and interactive use. Watch a file’s size. Watch a database’s replication status. Enlist the aid of ‘ping’ or ‘curl’ and watch a remote server.

But await, there is more. Of course the expression may be more useful than a simple and always True constant. The following example searches a file every minute for the word “Done” alone with itself on a Line. When that quarry be found, the ‘while’ loop successfully exits and the remaining statement executeth, namely, a subsequent and secondary scripte be run.

ℜ> while [ "$x" != "Done" ] > do > x=`grep Done output.logge` > sleep 60 > done && run_scripte_ii.sh
A Parrot

But await, there be still more! For even simple enumerated looping may be easily achieved, with the aid of the simple tool ‘let’, ell ee tee, the Arithmetic Evaluator. Note two things, that the shell variable ought be initialized prior to the ‘while’ statement, and that ‘-lt’, dash ell tee, tests for a value which be Less Than.

ℜ> i=1 ℜ> while [ $i -lt 5 ] > do > echo "Hail Mary num. $i" > let i=$i+1 > done Hail Mary num. 1 Hail Mary num. 2 Hail Mary num. 3 Hail Mary num. 4 ℜ> _

Ctrl-D, Amen.

An Antelope, about 1250 - 1260, English
A Parrot, about 1250 - 1260, English
Digital images courtesy of the Getty’s Open Content Program

~ this page pub. 15 December 2013 ~
« previouse page: Sponsors ~ Table of Contentes ~ next page: Wyld Kingdom: bonnacons »