POSIX-Compliant Way to Scope Variables to a Function in a Shell Script

前端 未结 7 689
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 00:27

Is there a POSIX Compliant way to limit the scope of a variable to the function it is declared in? i.e.:

Testing()
{
    TEST=\"testing\"
}

Testing
echo \"T         


        
7条回答
  •  抹茶落季
    2020-12-08 01:09

    Dude. You guys are going crazy with all this! This is built into the design of POSIX functions declarations.

    If you would like a variable declared in the parent scope, to be accessible in a function, but leave its value in the parent scope unchanged, simply:

    Declare your function using an explicit subshell, i.e., use a

    • subshell_function_declaration() ( with=parentheses ), not

    • inlined_function_declarations() { with=braces ;}


    Which is the same behavior of inline grouping vs. subshell grouping, throughout the entire language. BTW.


    { [ $that = $is ] && how=grouping_works || ! $SHELL ;} || (exit 1), y'know?

提交回复
热议问题