2

Recently while working I noticed this behavior of local variables. I wrote this piece of code to simplify my doubt.

foo () {
    echo "This is moo : $MOO_VAR"
}

moo () {
    local MOO_VAR="Hi MOO!"
    foo
}

echo "calling moo."
moo

I can't understand how function foo can access the value of local variable MOO_VARof function moo, although foo cannot change the value of MOO_VAR . I can't find any explanation for this behavior. Can somebody explain why this happens ?

1 Answer 1

2

This is documented behaviour of bash. It would seem that local really just means, restore this variable to its previous state at the end of the function. Due to how variables are implemented in bash (stored in a global namespace), this means the variables cannot be hidden from children without first unsetting the variable before each function call and then reinstating it afterwards.

Sign up to request clarification or add additional context in comments.

5 Comments

But you can define a local variable in foo of the same name, its value will be restored at the end of the function.
Yes, I know that. But why is the local variable of moo accessible to foo. Shouldn't the scope of MOO_VAR be inside moo itself.
Dunes, so if I change the value of MOO_VAR inside foo , it will change its value as it is stored in global namespace, and when the function ends it will just reinitialize it to its original value so that its usage in moo remains unaffected ?
@molecule Because bash is a scripting language, not a fully fledged programming language. If you want a fresh scope for each function call then try something like python.
Put another way, bash is a dynamically scoped language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.