The while loop
Up until now, we have dealt with loops that have a fixed number of iterations. The reason is simple – if you are using a for
loop, you need to specify for what values your loop is going to run, or what values your variable is going to have while in the loop.
The problem with this approach to looping is that sometimes you don't know in advance how many iterations you are going to need to do something. This is where the while
loop comes into play.
Getting ready
The most important thing you need to know about the while
loop is that it does its testing at the start of the loop. This means that we need to structure our script to run while something is true. This also means that we can make a loop that will never get executed; if we create a while
loop that has a condition that is not met, bash
is not going to run it at all. This has a number of great advantages, since it gives us the flexibility to use our loop as many times as we need without thinking...