[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: |
alex xmb sw ratchev |
Subject: |
Re: using a variable from global scope or checking whether it is local to some scope |
Date: |
Thu, 19 Oct 2023 22:17:31 +0200 |
to answer the topic question ..
.. maybe something with compgen
but , .. another answer
in ur code , force global / local whenever u need it
~ $ ( declare -g a ; a=2 ; declare -p a ; declare a ; declare -p a ; a=3 )
declare -- a="2"
declare -- a="2"
~ $
sadly i didnt find difference there
but just declare -g or non -g when u need
On Thu, Oct 19, 2023, 17:13 Christoph Anton Mitterer <calestyo@scientia.org>
wrote:
> Hey.
>
> Are there ways to achieve either of the following in a function:
>
> 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.
>
>
>
>
> The only thing that came to my mind for (2) was using
> local -p var
> but the problem with that seems to be that it shows only such variables
> as local, that were made local in the same function scope (i.e. not in
> a calling function):
>
> Still works at the current function scope:
> foo() { local var=a; [ -n "$(local -p var 2>/dev/null)" ]; echo $?; }
> => $? = 0
> foo() { var=a; [ -n "$(local -p var 2>/dev/null)" ]; echo $?; }
> => $? = 1
>
>
> but longer when made local in a calling scope:
> foo() { [ -n "$(local -p var 2>/dev/null)" ]; echo $?; }
>
> bar() { local var=a; foo; }
> => $? = 1
> bar() { var=a; foo; }
> => $? = 1
>
>
>
>
> For (1) the best I was able to come up with was:
> var=global
>
> foo1()
> {
> echo foo1 beg $var
> local var=foo1
> echo foo1 mid $var
> foo2
> echo foo1 end $var
> }
>
> foo2()
> {
> echo foo2 beg $var
> local var=foo2
> echo foo2 mid $var
> bar
> echo foo2 end $var
> }
>
>
>
> bar()
> {
> echo bar beg $var
> unset -v var
> #unset -v var
> echo bar mid $var
> var=new
> echo bar end $var
> }
>
> echo glb beg $var
> foo1
> echo glb end $var
>
>
> The core idea is:
> AFAIU, when the var is not made local in the *same* scope, and only
> then, I can use unset -v to unset that from the outer scope and break
> out, to the next earlier scope where var was declared.
>
> [Is this even documented behaviour or is it just the way it works now
> and may change in principle?]
>
> But there's obviously the problem, I don't know how many there are. I
> also don't think it would work to unset as often as there are elements
> in FUNCNAME. Not every function may make it local, and I'd end up
> unsetting the global one.
>
>
>
>
> Oh and side question:
> Is it possible to prevent such break out via unset?
>
>
> Thanks,
> Chris.
>
>