bug-bash
[Top][All Lists]
Advanced

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

Re: Passing variables by reference conflicts with local


From: Chet Ramey
Subject: Re: Passing variables by reference conflicts with local
Date: Sat, 28 Apr 2012 22:31:56 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:11.0) Gecko/20120327 Thunderbird/11.0.1

On 4/23/12 4:56 AM, Clark Wang wrote:

> When I revisit this 2 years old thread I don't understand why following
> foo() function does not output the global var:
> 
> $ cat foo.sh
> var=global
> foo()
> {
>     local var=foo
>     unset var
>     echo foo: $var
> }
> bar_unset()
> {
>     unset var
> }
> bar()
> {
>     local var=bar
>     bar_unset
>     echo bar: $var
> }
> foo
> bar
> $ bash foo.sh
> foo:
> bar: global
> $
> 
> In foo() it unsets its local var so why doesn't the subsequent $var refer
> to the global var?

Greg's explanation in a subsequent message was pretty close.  Back a number
of years ago (16, to be exact), bash behaved like you expect.  Between
bash-1.14 and bash-2.0, I changed it in response to a number of bug reports
that complained that a variable declared local in a function wasn't local
when assigned a value in the function after being unset.  Bash keeps a
placeholder in the function's variable context so subsequent references to
that unset variable don't traverse back through the call chain.  This
placeholder affects functions called by the function unsetting the local
variable in the way you would expect dynamic scoping to work.

This only affects the current function, though: an unset issued from
farther down the call chain, as you discovered, will unset the local
variable without creating a placeholder.

Chet

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU    address@hidden    http://cnswww.cns.cwru.edu/~chet/



reply via email to

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