Discussion:
[Help-bash] Is there a way to access a global variable once a local variable with the same name is declared?
Peng Yu
2018-12-04 23:25:29 UTC
Permalink
Hi,

Is there a way to access a global variable once a local variable with
the same name is declared? Thanks.

$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
function f {
local x
declare -p x
# I like to access the global x as well here.
}
x=1
f
declare -p x

$ ./main.sh
function f {
local x
declare -p x
}
x=1
f
declare -- x
declare -p x
declare -- x="1"
--
Regards,
Peng
Grisha Levit
2018-12-06 18:00:51 UTC
Permalink
Post by Peng Yu
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.
Peng Yu
2018-12-07 19:31:14 UTC
Permalink
Post by Grisha Levit
$ g() { declare -n $1=$1; printf %s "${!1}"; } 2>/dev/null
$ x=1; f() { local x=2; g x; }; f
1
I don't see the "1" printed at the end. Anything wrong?

--
Regards,
Peng
Grisha Levit
2018-12-07 19:48:46 UTC
Permalink
This is actually only in bash 5.
Post by Peng Yu
Post by Grisha Levit
$ g() { declare -n $1=$1; printf %s "${!1}"; } 2>/dev/null
$ x=1; f() { local x=2; g x; }; f
1
I don't see the "1" printed at the end. Anything wrong?
--
Regards,
Peng
Peng Yu
2018-12-07 19:53:49 UTC
Permalink
Where is 5? I only see 4.4.

https://github.com/bminor/bash
Post by Grisha Levit
This is actually only in bash 5.
Post by Peng Yu
Post by Grisha Levit
$ g() { declare -n $1=$1; printf %s "${!1}"; } 2>/dev/null
$ x=1; f() { local x=2; g x; }; f
1
I don't see the "1" printed at the end. Anything wrong?
--
Regards,
Peng
--
Regards,
Peng
Grisha Levit
2018-12-07 20:03:25 UTC
Permalink
That's some unofficial mirror. Official repo is at
https://git.savannah.gnu.org/cgit/bash.git, check the devel branch.
Post by Peng Yu
Where is 5? I only see 4.4.
https://github.com/bminor/bash
Post by Grisha Levit
This is actually only in bash 5.
Post by Peng Yu
Post by Grisha Levit
$ g() { declare -n $1=$1; printf %s "${!1}"; } 2>/dev/null
$ x=1; f() { local x=2; g x; }; f
1
I don't see the "1" printed at the end. Anything wrong?
--
Regards,
Peng
--
Regards,
Peng
Chet Ramey
2018-12-07 20:46:17 UTC
Permalink
Post by Grisha Levit
That's some unofficial mirror. Official repo is at
https://git.savannah.gnu.org/cgit/bash.git, check the devel branch.
For alpha and beta releases, use the bash-5.0-testing branch. The devel
branch is for ongoing development.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Loading...