help-bash
[Top][All Lists]
Advanced

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

Re: using a variable from global scope or checking whether it is local t


From: Greg Wooledge
Subject: Re: using a variable from global scope or checking whether it is local to some scope
Date: Fri, 20 Oct 2023 07:30:48 -0400

On Fri, Oct 20, 2023 at 09:50:58AM +0900, Koichi Murase wrote:
> > Unfortunately, we cannot use `declare -g gvar' to get the value in the
> > global environment, [...]
> 
> Sorry, this is a typo of `declare -p -g gvar'. Anyway, `declare'
> cannot be used to get the hidden value in the global context.

The very first thing I tried was "declare -g var", with the intent of
creating a local variable which would "reference" the global one.
In hindsight, I can see why this would never work.  Bash simply doesn't
prsent variables in this way.  The only time you can access the global
variable is if there *aren't* any locals shadowing it.  With apparently
the single exception of "declare -g var=value" to assign to the global
in a write-only manner (which I did not previously know).

The reason I even tried this is because Tcl has a "global" command
which does this exact thing (creating a local variable that references
a global one), as well as "upvar" which does that as well, and can also
reference local variables in parent, grandparent, etc. functions.
Being accustomed to that, it's easy to fall into the trap of assuming
other languages will have a similar feature.



reply via email to

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