Bourne variable unset outside while()

Matthew Seaman matthew at FreeBSD.org
Thu May 8 21:07:39 UTC 2014


On 08/05/2014 19:48, Rick Miller wrote:
> I have a Bourne shell script that echoes the contents of a data structure
> to a while() loop that iterates over the data and is expected to append a
> string from the current iteration to a different list.  Inside the while(),
> it works fine, but echo'ing the list outside the loop produces empty
> output.  I expect the variable to maintain it's final state after
> processing the while(), but it does not appear to be doing so.
> 
> /** The script **/
> 
> #! /bin/sh -x
> 
> fs="freebsd-ufs gprootfs 1G
> freebsd-swap gpswapfs 1G
> freebsd-ufs gpvarfs 1G";
> 
> echo "${fs}" |
> while read -r fstype fslabel fssize; do
> 
>         labels="${labels} ${fslabel}";
>         echo "${labels}";
> 
> done
> 
> echo -e "\nlabels = ${labels}";
> 
> /** End the script **/
> 
> The output from this script is at http://pastebin.com/mxNLLWtm
> 
> This almost appears to be an issue with scope, but I've not encountered
> this before, especially in such simple context.  I must be missing
> something obvious and just looking for feedback to send me off in the right
> direction.

Piping input to a 'while read' in shell implies that the content of the
while loop will be run in a sub-shell.  Meaning it can't affect the
value of any variables in the parent process, ie. outside the while loop.

This is a fairly obscure gotcha in shell programming -- finding out
about it is like one of those rite of passage on the way to shell-godhood.

Either put the tail of your script inside the while loop, using some
sort of if- condition or other wise arranging for it to only run the
last time around the loop, or print the values you need as a statement
you can eval, or use a temporary file or ... Well, there are many ways
to solve this problem.  Good luck and have fun.

	Cheers,

	Matthew

-- 
Dr Matthew J Seaman MA, D.Phil.
PGP: http://www.infracaninophile.co.uk/pgpkey


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 1036 bytes
Desc: OpenPGP digital signature
URL: <http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20140508/31728635/attachment.sig>


More information about the freebsd-questions mailing list