[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Is there a way to access a global variable once a local
From: |
Grisha Levit |
Subject: |
Re: [Help-bash] Is there a way to access a global variable once a local variable with the same name is declared? |
Date: |
Thu, 6 Dec 2018 13:00:51 -0500 |
On Tue, Dec 4, 2018 at 6:26 PM Peng Yu <address@hidden> wrote:
> Is there a way to access a global variable once a local variable with
> the same name is declared? Thanks.
>
A local circular nameref will resolve to the global variable of the same
name.
So you can make a function to retrieve a global variable's value, like:
$ g() { declare -n $1=$1; printf %s "${!1}"; } 2>/dev/null
$ x=1; f() { local x=2; g x; }; f
1
You will need something a bit fancier for arrays, depending on how exactly
you want to access their values.