On Thu, Aug 31, 2023 at 10:38:55PM +0300, queency3 jones wrote: > > > function sub { aa=8;return_value=$aa; } > > > function sub { aa=8; } > > > > > > function main { aa=3;sub;aa=$(($aa+1));printf "$aa\n"; }
> i don't think that main is significant when it declared in "Bash" but even > though, > if you change the function main , to function ain the $aa should be local > , but it ain't !! Bash uses dynamic variable scope. If a function needs to retrieve the value from a variable, it looks at its own local variables first, then at its caller's local variables, then it's caller's caller's variables, and so on up the stack. Since main calls sub, "aa=8" in sub look for a local variable in sub. There isn't one, so it looks for a local variable in main. And if there isn't one in main, then it looks in main's caller, which happens to be the global scope. If you add "local aa" inside main, this doesn't change anything inside main or sub. sub will find the local variable aa inside main, and it will change that one, instead of the global one. The difference here is that the modified aa is no longer visible at the global scope. It "disappears" when main is finished. If you add "local aa" inside sub, this *does* change the result. Now, aa=8 is executed upon the copy of aa that's local to sub, rather than the one that's local to main. So, main's copy remains set to 3. If you want *every* copy of aa to be treated as a local variable within its own function, you must declare it as local inside every function where it's used. That's the way bash works: every variable is non-local by default.