shell - Does Bash have private stack frames for recursive function calls? -


consider following code:

recursion_test() {     local_var=$1     echo "local variable before nested call: $local_var"      if [[ $local_var == "yellow" ]];         return     fi      recursion_test "yellow"      echo "local variable changed nested call: $local_var" } 

output:

local variable before nested call: red local variable before nested call: yellow local variable changed nested call: yellow 

in other programming languages such java each method invocation has separate private stack frame on local variables kept. nested invocation of method can't modify variables in parent invocation.

in bash invocations share same stack frame? there way have separate local variables different invocations? if not, there workaround write recursive functions 1 invocation not affect other?

you want local builtin. try local local_var=$1 in example.

note: still have careful local isn't private in c stack variable. it's more javascript's var means called [child] function can @ [vs. js's let, is totally private].

here's example:

recursion_test() {     local local_var=$1     echo "local variable before nested call: $local_var"      # note: if use other_func_naughty instead, infinite recursion     other_func_nice      if [[ $local_var == "yellow" ]];         return     fi      recursion_test "yellow"      echo "local variable changed nested call: $local_var" }  other_func_naughty() {     local_var="blue" }  other_func_nice() {     local local_var="blue" }  recursion_test red 

so, if use local <whatever>, sure consistent (i.e. functions declare same way)


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -