Using local variables from “child” functions

前端 未结 2 1710
后悔当初
后悔当初 2021-01-15 08:53

Consider following code:

function child()
{
    echo $var
}

function parent()
{
    local var=5
    child
}

I\'ve tested it on my machine

2条回答
  •  借酒劲吻你
    2021-01-15 09:31

    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"
    

提交回复
热议问题