help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] How to make variable set in () accessible outside?


From: Peng Yu
Subject: Re: [Help-bash] How to make variable set in () accessible outside?
Date: Thu, 3 May 2012 06:06:11 -0500

On Thu, May 3, 2012 at 12:16 AM, Dan Douglas <address@hidden> wrote:
> On Wednesday, May 02, 2012 11:21:03 PM Peng Yu wrote:
>> On Wed, May 2, 2012 at 11:12 PM, Dan Douglas <address@hidden> wrote:
>> > On Wednesday, May 02, 2012 10:37:04 PM Peng Yu wrote:
>> >> Hi,
>> >>
>> >> (export XXX=a)
>> >> echo $XXX
>> >>
>> >> In the above code, the echo command will print nothing. I'm wondering
>> >> if there is a way make the variable set in () accessible outside.
>> >
>> > Any time there's a subshell involved, you're effectively dealing with a
>> > separate independent process with its own shell execution environment.
>> > There's no way to make anything inside directly accessible to the
>> > outside.  The only ways to interact with a subshell are the same as with
>> > any other external command - mostly that's via standard streams.
>> >
>> > Lots of examples here: http://mywiki.wooledge.org/BashFAQ/002
>> >
>> > Also remember that export is a POSIX special builtin, and Bash
>> > (thankfully,
>> > IMO) doesn't follow the spec on this by default.
>> >
>> >  ~ $ ( bash -c 'xxx=a export a; echo "$xxx"' )
>> >
>> >  ~ $ ( bash --posix -c 'xxx=a export a; echo "$xxx"' )
>> > a
>> >
>> > The above isn't related to a subshell issue.
>> >
>> > Is there a specific problem you're trying to solve?
>>
>> I need pass something computed in () to the enclosing environment. The
>> walkaround that I found was to use a tempfile.
>
> Normally people only suffer this problem in unavoidable cases like when using 
> pipes or process substitutions.
> Ideally the explicit subshell should be avoided if at all possible, e.g. 
> ,using a function and local variables for encapsulation.

http://lists.gnu.org/archive/html/help-bash/2012-02/msg00000.html

See the example of holdcpu.sh in the above mail (holdcpu.sh was
mistyped to holdcup.sh there.)

> There are many, many other workarounds depending on the situtation. Just 
> reading the vars through a pipe usually works.
> If there's absolutely no alternative than to move around variables with 
> temporary files, a hack I commonly use
> (and wouldn't commonly advertise to others) is to write to an empty 
> herestring. This shows both:
>
> shopt -s lastpipe; { { x=5 let x+=y=5; declare -p x; printf %s "$y" 
> >/dev/stdin; } | . /dev/stdin; declare -p x; IFS= read -rd -- y; declare -p 
> y; } <<<''
>
> As I recall, looking at this in strace, bash doesn't actually fsync, and up 
> to a certain size this is pretty fast (even if TMPDIR doesn't happen to be on 
> a tmpfs)
> --
> Dan Douglas



-- 
Regards,
Peng



reply via email to

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