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

前端 未结 7 636
被撕碎了的回忆
被撕碎了的回忆 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:26

    Define the functions using the function myfunc { syntax, and use typeset myvar to define your variables. If you define functions that way rather than using the myfunc(){ syntax, all of the common Bourne shells (bash, zsh, ksh '88 and '93) will localize variables defined with typeset (and aliases to typeset like integer).

    Or reinvent the wheel. Whichever floats your boat. ;)

    EDIT: while the question asks for POSIX, and this is not a POSIX-compliant function definition syntax, the person who asked indicates in a later comment that he's using bash. The use of "typset" in combination with the alternative function definition syntax is the best solution there, as the true POSIX mechanism requires the additional overhead of forking a new subshell.

    0 讨论(0)
提交回复
热议问题