3

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?

4
  • From man bash When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. Commented Nov 17, 2016 at 15:05
  • Why is this a comment and not an answer? Commented Nov 17, 2016 at 15:06
  • 1
    From man sh The shell uses dynamic scoping, so that if the variable x is made local to function f, which then calls function g, references to the variable x made inside g will refer to the variable x declared inside f, not to the global variable named x. Commented Nov 17, 2016 at 15:07
  • Can't be bothered writing a full answer soz. Commented Nov 17, 2016 at 15:08

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

0

Just complimenting what user 123 already mentioned in the comments

From bash man pages

Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller.

bash3.2.25->cat function.ss 
#!/bin/bash
function child()
{
        echo "child function called"
        echo $var
}


function parent_global()
{
        echo "parent_global called, child invoked outside parent"
        var=5
}

function parent()
{
        echo "parent called, child invoked inside parent"
        local var=5
        child
}

parent
parent_global
child
bash3.2.25->./function.ss 
parent called, child invoked inside parent
child function called
5
parent_global called, child invoked outside parent
child function called
5

So unless specified otherwise (the local builtin), variables are visible outside the function scope, global if you will.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.