Consider the following code:
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"
}
Output:
Local variable before nested call: red
Local variable before nested call: yellow
Local variable changed by nested call: yellow
In other programming languages such as Java each method invocation has a separate private stack frame on which local variables are kept. So nested invocation of a method can't modify variables in the parent invocation.
In Bash do all invocations share the same stack frame? Is there a way to have separate local variables for different invocations? If not, is there a workaround to write recursive functions properly so that one invocation does not affect the other?
You want the local builtin. Try local local_var=$1 in your example.
NOTE: You still have to be careful as local isn't completely private as in a C stack variable. It's more like javascript's var which means any called [child] function can get at it [vs. js's let, which is totally private].
Here's an example:
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
So, if you use local <whatever>, just be sure to be consistent (i.e. all functions declare it the same way)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With