Using local variables from “child” functions

前端 未结 2 1709
后悔当初
后悔当初 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:18

    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.

提交回复
热议问题