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: Thu, 19 Oct 2023 12:47:01 -0400

On Thu, Oct 19, 2023 at 05:12:00PM +0200, Christoph Anton Mitterer wrote:
> 1) I want to make sure that a variable is used from the global scope
>    even if my function was possibly (which I don't know) called from
>    another function (which may have made the variable local itself.
> 
> 2) Or at least find out, whether in a function, the variable is
>    actually from the global scope or not.

I don't think either of these can be achieved non-destructively.
You could just keep unsetting the variable until it no longer exists,
but that destroys all the local instances of the variable throughout
the call stack.

My first thought was to use "declare -g var" inside the innermost
function, but this doesn't work.  Or at least, I couldn't make it work.

If you really need this functionality, I don't think bash is suited.
Tcl's "upvar" command can do this exact thing, and more.  I don't know
of any analogous feature in bash.

> Oh and side question:
> Is it possible to prevent such break out via unset?

I recommend checking out Freddy Vulto's prior work.

https://fvue.nl/wiki/Bash:_Passing_variables_by_reference
https://fvue.nl/wiki/Bash:_Unset



reply via email to

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