2016-01-21 64 views
2

考虑下面的代码:Bash是否有用于递归函数调用的私有堆栈框架?

recursion_test() { 
    local_var=$1 
    echo "Local variable before nested call: $local_var" 

    if [[ $local_var == "yellow" ]]; then 
     return 
    fi 

    recursion_test "yellow" 

    echo "Local variable changed by nested call: $local_var" 
} 

输出:

Local variable before nested call: red 
Local variable before nested call: yellow 
Local variable changed by nested call: yellow 

在其它的编程语言,比如Java每个方法调用具有其上局部变量保存一个单独的私人堆栈帧。因此,方法的嵌套调用不能修改父调用中的变量。

在Bash中,所有的调用都共享相同的堆栈框架吗?有没有办法让不同的调用有单独的局部变量?如果没有,是否有一个解决方法来正确编写递归函数,以便一个调用不会影响另一个?

回答

5

你想要内建local。在你的例子中尝试local local_var=$1

注意:您仍然必须小心,因为local不是完全私密的,如在C堆栈变量中。这更像是javascriptvar这意味着任何被称为[子]功能可以得到它[vs. js的let,其中完全私人]。

下面是一个例子:

recursion_test() { 
    local local_var=$1 
    echo "Local variable before nested call: $local_var" 

    # NOTE: if we use other_func_naughty instead, we get infinite recursion 
    other_func_nice 

    if [[ $local_var == "yellow" ]]; then 
     return 
    fi 

    recursion_test "yellow" 

    echo "Local variable changed by nested call: $local_var" 
} 

other_func_naughty() { 
    local_var="blue" 
} 

other_func_nice() { 
    local local_var="blue" 
} 

recursion_test red 

所以,如果你使用local <whatever>,只是一定要保持一致(即所有函数声明同样的方式)

相关问题