Bash Shell Scripting/Loops

Often we want to run the same sequence of commands, over and over again, with slight differences. For example, suppose that we want to take all files named  and rename them to   ("backup"). We can use file-expansion to get the list of files named, but how do we use that list? There's no obvious command containing, say,, that would perform the three moves we need. What we need is a  loop:

The above takes the variable, and assigns it in turn to each word in the expansion of. Each time, it runs the body of the loop. In other words, it is equivalent to the following:

There is nothing special here about filename expansion; we can use the same approach to iterate over any other argument-list, such as the integers 1 through 20 (using brace expansion):

or the positional parameters :

In fact, that specific case is so common that Bash provides the equivalent shorthand, with   being implied. (But it's probably better to use the explicit form anyway.)

Another kind of loop is the  loop. It is similar to an  statement, except that it loops repeatedly as long as its test-command continues to be successful. For example, suppose that we need to wait until the file  is deleted. One approach is to "sleep" for a few seconds, then "wake up" and see if it still exists. We can loop repeatedly in this fashion:

Conversely, we can use an  loop to loop until a given command is successful; for example, the reverse of the above might be:

Of course, this is the same as combining  with , but in some cases it may be more readable.
 * Just like,   judges   or   in the same way. Try it out yourself.