Looping for a While

Problem

You want your shell script to perform some actions repeatedly as long as some condition is met.

Solution

Use the while looping construct for arithmetic conditions:

while (( COUNT < MAX ))
do
    some stuff
    let COUNT++
done

for filesystem-related conditions:

while [ -z "$LOCKFILE" ]
do
    some things
done

or for reading input:

while read lineoftext
do
    process $lineoftext
done

Discussion

The double parentheses in our first while statement are just arithmetic expressions, very much like the $(( )) expression for shell variable assignment. They bound an arithmetic expression and assume that variable names mentioned inside the parentheses are meant to be dereferenced. That is, you don’t write $VAR, and instead use VAR inside the parentheses.

The use of the square brackets in while[ -z"$LOCKFILE" ] is the same as with the if statement—the single square bracket is the same as using the test statement.

The last example, while read lineoftext, doesn’t have any parentheses, brackets, or braces. The syntax of the while statement in bash is defined such that the condition of the while statement is a list of statements to be executed (just like the if statement), and the exit status of the last one determines whether the condition is true or false. An exit status of zero, and the condition is considered true, otherwise false.

A read statement returns a 0 on a successful read and a -1 on end-of-file, which means that the while will find it true for any successful read, but when the end ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.