How to Use Local Variables in Function in Bash
In Bash, declare local variables inside a function using the
local keyword before the variable name. This limits the variable's scope to the function, preventing it from affecting or being affected by variables outside the function.Syntax
Use the local keyword inside a function to declare a variable that only exists within that function's scope.
local variable_name=value: Declares a local variable and optionally assigns a value.- The variable is not accessible outside the function.
bash
function example_function() { local my_var="Hello" echo "$my_var" }
Example
This example shows how a local variable inside a function does not affect a variable with the same name outside the function.
bash
my_var="Outside" echo "Before function call: $my_var" function test_local() { local my_var="Inside" echo "Inside function: $my_var" } test_local echo "After function call: $my_var"
Output
Before function call: Outside
Inside function: Inside
After function call: Outside
Common Pitfalls
One common mistake is forgetting to use local, which makes the variable global and can overwrite variables outside the function.
Another issue is using local outside a function, which causes an error.
bash
my_var="Global" function wrong_usage() { my_var="Changed" echo "Inside function without local: $my_var" } wrong_usage echo "Outside after function call: $my_var" function correct_usage() { local my_var="Local" echo "Inside function with local: $my_var" } correct_usage echo "Outside after correct usage: $my_var"
Output
Inside function without local: Changed
Outside after function call: Changed
Inside function with local: Local
Outside after correct usage: Changed
Quick Reference
| Command | Description |
|---|---|
| local var=value | Declare a local variable inside a function with an optional initial value |
| local var | Declare a local variable without assigning a value |
| var=value | Declare or assign a global variable (outside or inside function without local) |
| local outside_function | Causes error: local can only be used inside functions |
Key Takeaways
Use the local keyword inside functions to declare variables scoped only to that function.
Local variables prevent accidental changes to variables outside the function.
Forgetting local makes variables global, which can cause bugs.
local cannot be used outside functions; it will cause an error.
Always declare variables local inside functions unless you want to modify global variables.