while loops (was Re: Shell scripts - EOF on read)

Ubben Greg bink at aplcen.apl.jhu.edu
Sun Apr 30 10:53:35 AEST 1989


In article <7353 at nuchat.UUCP> steve at nuchat.UUCP (Steve Nuchia) writes:
>In article <869 at twwells.uucp> bill at twwells.UUCP (T. William Wells) writes:
>>	while true
>>	do
>>		read foo
>>		echo "<$foo>"
>>	done
>
>Try this one [instead]:
>
>	while read foo
>	do
>		echo $foo
>	done

This well-written response corrects a bad programming style I'd like to rag
on.  This is the tendency for many shell programmers (including some self-
proclaimed Unix masters) to code a naturally terminating loop misleadingly
as an infinite WHILE loop.  Then because the WHILE's built-in termination has
been bypassed, an explicit BREAK statement must be hacked in to terminate it.
Though BREAK is not nearly as bad as GOTO, it is worse than not using it at
all.  Here is a skeleton of this unstructured style:

	while true
	do
		SOME PROCESSING...
		if [ TERMINATION CONDITION ]; then
			break
		fi
		SOME MORE PROCESSING...
	done

An even worse style is used by programmers whose habits have carried over
from languages that don't even offer a break-like statement:

	SOME PROCESSING...
	while [ NOT TERMINATION CONDITION ]
	do
		SOME MORE PROCESSING...
		SOME PROCESSING...
	done

This method needlessly duplicates code (which might be many lines), making
it less maintainable.

IMHO, the Bourne shell's while loop is one of the best designed while loops
of any language, C not excluded.  Shell is one of the few languages in which
the common n-and-a-half-times loop can be coded simply and elegantly.  And
for the record, this is how it's done:

	while
		SOME PROCESSING...
		test NOT TERMINATION CONDITION
	do
		SOME MORE PROCESSING...
	done

("While" can be replaced by "until" to negate the test condition.)

I hope this tip is taken constructively, and that responses are in the
same spirit.


					-- Greg Ubben
					   bink at aplcen.apl.jhu.edu



More information about the Comp.unix.wizards mailing list