局部变量重新赋值后是否仍保持局部性?Bash函数场景验证
Great questions about Bash local variables—let's break this down clearly!
Absolutely! Once you declare a variable as local inside a Bash function, that variable is tied to the function's scope for its entire lifetime in that function. Reassigning it later (without the local keyword) only updates the value of the local variable, not any global variable with the same name. The local keyword only needs to be used once when you first initialize or declare the variable in the function to mark it as local.
foo remain "unmodified" in your example? Yes, your external foo variable will definitely stay set to "unmodified" after running that command. Let's walk through why:
- Inside
ql_do_x, you first declarelocal foo="bar"—this creates a local variablefoothat shadows the global/externalfoofor the duration of the function. - When you do
foo="zam"inside theifblock, you're only updating that localfoovariable, not the one outside the function. - After the function finishes running, the local
foois discarded, and the original externalfooremains untouched.
If you test this directly, you'll see it in action:
ql_do_x(){ local foo="bar"; if true; then foo="zam"; fi } foo="unmodified" ql_do_x echo "$foo" # Outputs: unmodified
内容的提问来源于stack exchange,提问作者Alexander Mills

