While

From LQWiki
Jump to navigation Jump to search

while is a construct used in many programming languages to perform a loop repeatedly until a condition is met.

For example, in C one could write:

while (condition) {
  some code
}

some code would be executed repeatedly until condition became false. If condition was false to start with, then some code would be skipped completely.

A while loop is equivalent to:

label1: if (! condition) {
  goto label2
}
  do something
label2:
  code continues

The while loop is an unbound loop, meaning that the number of iterations through the loop is not set before the loop is executed. This means that various bugs can cause the loop to enter infinite recursion, where the exit condition is never met and the loop runs forever. On the other hand, some algorithms can only be implemented using unbounded loops.

'do' While Loops

The C languages also uses the syntactically similar do...while loop, like this:

do {
  some code
} while (condition)

This is similar, except that some code is always executed at least once, and the exit condition is worked out at the end of the loop instead.

A do while loop is equivalent to:

label1: some code
 if (condition) {
   goto label1;
 }

In Shells

The BASH shell-scripting language has constructs for both while and its complement method, until.

The basic construct for a while loop in a BASH script is:

while some command
  do other command
done

Here, some command is executed. If its exit status is non-zero, the while statement ends. Otherwise, other command is executed, its exit condition is ignored, and then it goes back to executing some command again.

One simple example prints out the word “yes” repeatedly:

while true; do echo "yes"; done

This is one possible implementation of the basic yes command.