bug-bash
[Top][All Lists]
Advanced

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

Re: nameref and referenced variable scope, setting other attributes (was


From: Chet Ramey
Subject: Re: nameref and referenced variable scope, setting other attributes (was "local -g" declaration references local var in enclosing scope)
Date: Thu, 14 Mar 2024 11:09:09 -0400
User-agent: Mozilla Thunderbird

On 3/14/24 8:29 AM, Zachary Santer wrote:

Alright, that's all fair. But this?

On Sun, Mar 10, 2024 at 7:29 PM Zachary Santer <zsanter@gmail.com> wrote:

Additionally, a nameref variable referencing a variable declared in a calling 
function hides that variable in the scope of the function where the nameref 
variable is declared.

OK, let's go through it. I stripped non-essentials out of your script:

1 func_1 () {
2 local var_2='ICE CREAM'
3 func_2
4 printf '%s\n' "func_1:"
5 local -p var_2
6 }
7
8 func_2 () {
9 local -nl nameref_2='var_2'
10 nameref_2='MILKSHAKE'
11 printf '%s\n' "func_2:"
12 local -p nameref_2
13 local -p var_2
14 }
15
16 func_1

func_1 declares var_2 to be a local variable (2) and calls func_2 (3).
func_2 declares nameref_2 to be a local nameref (9) and assigns a value (10).

bash resolves the value of nameref_2 to var_2, and performs the assignment
as if it had been var_2=MILKSHAKE (10). Since var_2 is in the calling
scope, func_1's variable gets modified. There is no var_2 in func_2's
scope.

func_2 prints the value of nameref_2 in its scope (12).
func_2 attempts to print the value of var_2 in its scope (13). Since there
is no local variable at func_2's scope, it's not found.

func_1 displays the modified value (5) using `local -p'.

`local' always operates at the current function scope. `local -p' only
displays local variables that exist at the current function scope.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/

Attachment: OpenPGP_signature.asc
Description: OpenPGP digital signature


reply via email to

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