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:
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.
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.