bug-bash
[Top][All Lists]
Advanced

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

Re: bash: variables inside 'while'


From: Gabriel Zachmann
Subject: Re: bash: variables inside 'while'
Date: 31 Aug 2001 07:51:40 GMT
User-agent: slrn/0.9.7.0 (Linux)

On Thu, 30 Aug 2001 12:11:56 -0400, Paul Jarc <prj@po.cwru.edu> wrote:
>  This belongs on bash-bug.  Followup-To and Mail-Followup-To set.
>  
>  zach@cs.uni-bonn.de (Gabriel Zachmann) wrote:
>  >     cat file |
>  >     while read p l
>  >     do
>  >         xx=$p
>  >         echo xx=$xx
>  >         break
>  >     done
>  >     echo xx=$xx
>  
>  This is related to entry E4 in the bash FAQ.  Each element of a
>  pipeline is run in a separate process, so variable settings are in
>  effect only within that element.  Try this:
>    cat file | { while read p l; do ...; done; echo xx=$xx; }
>  Or this:
>    while read p l; do ...; done < file; echo xx=$xx
>  (but that will still break on some other sh'es.)

One more thought:

Your latter suggestion does not work when one wants to do something like

    cat file | sed ... | while read ....

The solution involving the use of {} clutters up your script with braces
pretty quickly if one wants to do a little bit more complicated things
after the while, like

    cat file | sed ... |
    while read f l
    do
        if [[ $f = ...]]
        then
            x=$f
            break
        fi
    done
    if [[ "$x" != "" ]]
    then
        cat file2 | sed ... |
        while
        ...
    else
        cat file3 | sed ... |
        while
    fi

I think, you get the idea.
Of course, one could solve this by using lots of temporary files, 
but that incurs its own complications, since one has to check
for permissions, generate unique temp file names, clean up, etc...
(after all, that's what pipes are for ;-)

cheers,
Gab.


-- 
/---------------------------------------------------------------------\
| And what if all of animated nature                                  |
| Be but organic Harps diversely fram'd,                              |
| That tremble into thought, as o'er them sweeps                      |
| Plastic and vast, one intellectual breeze,                          |
| At once the Soul of each, and God of all?  (Samuel Taylor Coleridge)|
|                                                                     |
| zach@cs.uni-bonn.de                 __@/'  Gabriel.Zachmann@gmx.net |
| web.informatik.uni-bonn.de/~zach    __@/'   www.gabrielzachmann.org |
\---------------------------------------------------------------------/



reply via email to

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