Lost Assignment of var in shell for loop with stdout redirection

jerryp at tektools.UUCP jerryp at tektools.UUCP
Sat Feb 7 03:53:40 AEST 1987


[I've restricted this followup to comp.unix.questions only.]

In article <354 at rlgvax.UUCP> dennis at rlgvax.UUCP (Dennis Bednar) writes:
> In summary, apparently
> 
> for i
> do
> 	var=xxx
> done >/tmp/tmpfile
> 
> causes the shell interpreter to run a sub-shell, and so the value
> of $var set in the middle of a for loop is lost if $var is referenced
> after the for loop.  IS THIS CONSIDERED TO BE A sh(1) bug?

You're right about the loop: it runs in a sub-shell.
(This is true with the Berkeley Bourne shell, at least.)
The same thing happens with redirected input, as in:

	someprog |
	while read line
	do
		...set some shell variables...
	done

shell variables set inside the loop won't be available outside of it.
I think it's a well-known bug [anyone vote for calling it a feature? :-)]

It's fixed, at least partially, in the Korn Shell.

--Jerry Peek, Tektronix, Inc.
US Mail:      MS 74-900, P.O. Box 500, Beaverton, OR 97077
uucp-style:   {allegra,decvax,hplabs,ihnp4,ucbvax}!tektronix!tektools!jerryp
Domain-style: jerryp at tektools.TEK.COM
Phone:        +1 503 627-1603



More information about the Comp.unix.questions mailing list