quilt-dev
[Top][All Lists]
Advanced

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

Re: [Quilt-dev] [OT] bash question


From: Andreas Gruenbacher
Subject: Re: [Quilt-dev] [OT] bash question
Date: Fri, 9 Sep 2005 00:47:23 +0200
User-agent: KMail/1.7.1

On Thursday 08 September 2005 23:49, John Vandenberg wrote:
> On 9/9/05, Jean Delvare <address@hidden> wrote:
> > Hi all,
> >
> > I have a half off-topic question about bash, and figured out that there
> > were some experts here who may come to my help :)
> >
> > It looks like, when using pipes in bash, the scope of variables changes.
> > Consider the following example:
> >
> > --- 8< ---
> > #!/usr/bin/bash
> >
> > for ((i = 0; i < 4; i++))
> > do
> >         n=$i
> > done
> >
> > echo "n=$n i=$i"
> > --- 8< ---
> >
> > This prints "n=3 i=4" as one would expect. However, if I change it to:
> >
> > --- 8< ---
> > #!/usr/bin/bash
        ^ bash commonly is in /bin
> >
> > for ((i = 0; i < 4; i++))
> > do
> >         n=$i
> > done \
> >
> > | cat
> >
> > echo "n=$n i=$i"
> > --- 8< ---
> >
> > This does print "n= i=", that is, the n and i variables are no more
> > defined past the loop. Can someone explain why? Is there a way to change
> > that behavior? I am in a case where I badly need the value of one inner
> > variable after such a construct.
>
> The ( ) syntax creates a sub-shell.  Variables can be exported into
> the sub-shell, but cant come back out.

The example doesn't use ( ) though; the for loop doesn't use a subshell. The 
issue here is the pipe, where each pipe command is run in its own sub-shell. 
This can be worked around with redirection though. The cat in the example 
doesn't make a lot of sense (it's useless). Think about this:

#! /bin/bash

set -x

i=1
echo $i

i=2 | i=3
echo $i

i=4 < <(i=5)
echo $i

i=6 <<EOF
$(i=7)
EOF
echo $i

-- Andreas.




reply via email to

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