Bash是否具有用于递归函数调用的私有堆栈帧?

Ksh*_*rma 3 bash shell recursion

请考虑以下代码:

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"
}
Run Code Online (Sandbox Code Playgroud)

输出:

Local variable before nested call: red
Local variable before nested call: yellow
Local variable changed by nested call: yellow
Run Code Online (Sandbox Code Playgroud)

在其他编程语言(如Java)中,每个方法调用都有一个单独的私有堆栈帧,其上保留了局部变量.因此,嵌套调用方法无法修改父调用中的变量.

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

Cra*_*tey 6

你想要local内置.试试local local_var=$1你的例子.

注意:您仍然必须小心,因为local不像C堆栈变量那样完全私有.它更像javascriptvar这意味着任何被称为[孩子]的功能都可以获得它[对比 js's 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
Run Code Online (Sandbox Code Playgroud)

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