O'Reilly logo

bash Cookbook by Cameron Newham, JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required