[Gllug] Bizarre shell behaviour

Alain Williams addw at phcomp.co.uk
Fri Nov 7 17:24:21 UTC 2003


On Fri, Nov 07, 2003 at 05:16:30PM +0000, Tethys wrote:
> 
> Take the following shell script. Run it:
> 
> 	#!/bin/sh
> 
> 	count=0
> 	while read var
> 	do
> 		count=1
> 	done < /etc/group
> 
> 	echo $count
> 
> Assuming /etc/group isn't empty (which it isn't), the script should
> echo 1, right? Well the answer is, it depends on the shell. Under
> bash, pdksh and genuine ksh, yes, it does. But under Bourne shell,
> it varies. Under AIX and OpenBSD, sure enough it echoes a 1. But
> under Solaris and Tru64, it echoes 0 instead.
> 
> It's related to the "< /etc/group". If you remove that, and externally
> pipe the contents into the script, it works.
> 
> Bizarre... any ideas why? Judicious use of debugging echo statements
> shows that count is indeed being set to 1 inside the loop, but is being
> reset to 0 when the loop exits.

Some shells will interpret that as:

	(while read var
	 do
		count=1
	 done) < /etc/group

ie the loop is done in another process, so the setting of count does not
happen in the parent shell. Try putting an echo of $$ in there - you may see a difference
from $$ outside of the loop.

-- 
Alain Williams

#include <std_disclaimer.h>

FATHERS-4-JUSTICE - Campaigning for equal rights for parents and the
best interests of our children. See http://www.fathers-4-justice.org

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list