Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using local variables from "child" functions

Consider following code:

function child()
{
    echo $var
}

function parent()
{
    local var=5
    child
}

I've tested it on my machine and it seems to work but I wasn't able to find anything definitive describing such usage of local variables. Namely, when I declare a local variable in one function and from that function I call some other function, can I use the variable in the latter (and even nest it deeper)? Is it legal in bash and is it standard for all versions?

like image 707
NPS Avatar asked Sep 04 '26 06:09

NPS


1 Answers

bash uses dynamic scoping. The value of var in child is not determined by where child is defined, but by where it is called. If there is no local definition in the body of child, the next place the shell looks is in the body of the function from which child is called, and so forth. The local modifier creates a variable in a function that is local to that call, so it does not affect the value of the variable from any enclosing scopes. It is, though, visible to any enclosed scope.

a () { echo "$var"; }
b () { local var="local value"; a; }

var="global value"
a  # outputs "global value"
b  # outputs "local value"
like image 111
chepner Avatar answered Sep 07 '26 01:09

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!