You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

局部变量重新赋值后是否仍保持局部性?Bash函数场景验证

Great questions about Bash local variables—let's break this down clearly!

1. Do local variables stay local after being reassigned?

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.

2. Will the external 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 declare local foo="bar"—this creates a local variable foo that shadows the global/external foo for the duration of the function.
  • When you do foo="zam" inside the if block, you're only updating that local foo variable, not the one outside the function.
  • After the function finishes running, the local foo is discarded, and the original external foo remains 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:58