help-bash
[Top][All Lists]
Advanced

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

Re: Understanding internal variable scope


From: Robert E. Griffith
Subject: Re: Understanding internal variable scope
Date: Sat, 28 May 2022 21:10:51 -0400
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Thunderbird/91.8.1

FYI, I think I answered these questions on my own today by printing the shell_variables context stack out and then calling the builtin from various context -- file global vs in a function and main script vs sourced script vs sourced from inside a function.

1) I find that when my loadable builtin is called from a bash function, sometimes... create a local variable... does not work.
My stupid mistake. I had forgotten that I started calling the builtin from a bash wrapper function so the variables were being made in that scope and then immediately went out of scope soon after the builtin returned.

2) There seems to be a difference between sourcing a script at global scope
I see now the issue is in weather the -g is specified when using "declare" at the global scope of an sourced script. Without the -g if source is called from a function, declare is in the context of that function so it creates a local variable that will go out of scope with the function. With -g it puts in in the global scope regardless of whether there is a function variable context.

--BobG


On 5/28/22 10:36, Robert E. Griffith wrote:
I would like to understand better the internal variable scopes in the bash source code. Do you know of any documentation or past emails I can read on it? I am pretty familiar with the code now but I think I have some misconceptions because sometimes functions do not act like I expect. Maybe the temporary scope is not quite like I think it is.

In particular, I have two issues that I dont understand.

1) I find that when my loadable builtin is called from a bash function, sometimes the following code works to create a local variable in the calling function and sometimes it does not. If I do "local myVariableName" before calling the builtin, it always receives hte value.

   bind_variable_value(make_local_variable("myVariableName",0), "SomeValue..., 0)

2) There seems to be a difference between sourcing a script at global scope as opposed to sourcing it from inside a bash function but I cant quite pin it down. Sometimes variables declared in the global scope "declare <myvar>" of a sourced script do not exist after sourcing the script but functions from the script always do.

--BobG




reply via email to

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