bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Variables from while/read loops not seen outside of loop


From: Chet Ramey
Subject: Re: Variables from while/read loops not seen outside of loop
Date: Tue, 13 Jul 2004 08:52:05 -0400
User-agent: Mozilla Thunderbird 0.7 (Macintosh/20040616)

peter.kielbasiewicz@philips.com wrote:

I have various HPUX shell scripts that use the technique below and I do need to port them to Linux.
In HPUX's Posix shell it  is common practice to parse files like:

cat $file | while read line
                  do
... parse lines and assign results to variables...
                  done
                  ... print formatted output of resulting variables...

Unfortunately this does not work at all in bash and I found the reason under FAQ E4. All variables set inside the while/read loop are not passed to the parent shell and thus are unset when I want to print my formatted result

There are two questions here:
1. How does HPUX manage to handle the problem

ksh is internally structured to run the last element of a pipeline in
the current shell, and HPUX's `posix shell' is based on ksh.

   2. How can I write a solution in bash which gives the desired result

There are a number of suggestions in the FAQ.  The easiest is to change

        cat $file | while ... ; do .... ; done

to

        while ... ; do ... ; done < $file

which does not create a subshell.

Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
( ``Discere est Dolere'' -- chet )
                                                Live...Laugh...Love
Chet Ramey, ITS, CWRU chet@po.cwru.edu http://tiswww.tis.cwru.edu/~chet/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]