Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
Home Bash Guide for Beginners Repetitive tasks The while loop | ||||||||||
See also: The for loop, The until loop | ||||||||||
Search the VIAS Library | Index | ||||||||||
The while loopThe while construct allows for repetitive execution of a list of commands, as long as the command controlling the while loop executes successfully (exit status of zero). The syntax is: while CONTROL-COMMAND; do CONSEQUENT-COMMANDS; done CONTROL-COMMAND can be any command(s) that can exit with a success or failure status. The CONSEQUENT-COMMANDS can be any program, script or shell construct. As soon as the CONTROL-COMMAND fails, the loop exits. In a script, the command following the done statement is executed. The return status is the exit status of the last CONSEQUENT-COMMANDS command, or zero if none was executed. ExamplesSimple example using whileHere is an example for the impatient:
Nested while loopsThe example below was written to copy pictures that are made with a webcam to a web directory. Every five minutes a picture is taken. Every hour, a new directory is created, holding the images for that hour. Every day, a new directory is created containing 24 subdirectories. The script runs in the background.
Note the use of the true statement. This means: continue execution until we are forcibly interrupted (with kill or Ctrl+C). This small script can be used for simulation testing; it generates files:
Note the use of the date command to generate all kinds of file and directory names. See the man page for more.
Using keyboard input to control the while loopThis script can be interrupted by the user when a Ctrl+C sequence is entered:
A here document is used to present the user with possible choices. And again, the true test repeats the commands from the CONSEQUENT-COMMANDS list over and over again. Calculating an averageThis script calculates the average of user input, which is tested before it is processed: if input is not within range, a message is printed. If q is pressed, the loop exits:
Note how the variables in the last lines are left unquoted in order to do arithmetic.
|
||||||||||
Home Bash Guide for Beginners Repetitive tasks The while loop |