0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Local Variables in Bash Scripts

In bash, use the local keyword inside a function to declare a variable that exists only within that function's scope. This prevents the variable from affecting or being affected by variables outside the function.
📐

Syntax

Use local variable_name=value inside a bash function to create a variable limited to that function's scope.

  • local: keyword to declare a local variable
  • variable_name: the name of the variable
  • =value: optional initial value assignment
bash
function example() {
  local my_var="Hello"
  echo "$my_var"
}
💻

Example

This example shows how a local variable inside a function does not affect a global variable with the same name.

bash
my_var="Global"

echo "Before function call: $my_var"

function test_local() {
  local my_var="Local"
  echo "Inside function: $my_var"
}

test_local

echo "After function call: $my_var"
Output
Before function call: Global Inside function: Local After function call: Global
⚠️

Common Pitfalls

One common mistake is declaring a variable inside a function without local, which makes it global and can overwrite variables outside the function.

Also, local only works inside functions; using it outside causes an error.

bash
my_var="Global"

function wrong_local() {
  my_var="Changed"
  echo "Inside function without local: $my_var"
}

wrong_local

echo "Outside after function: $my_var"

function correct_local() {
  local my_var="Local"
  echo "Inside function with local: $my_var"
}

correct_local

echo "Outside after correct_local: $my_var"
Output
Inside function without local: Changed Outside after function: Changed Inside function with local: Local Outside after correct_local: Changed
📊

Quick Reference

  • local var=value: Declare a local variable inside a function
  • Local variables exist only during the function execution
  • Using local outside a function causes an error
  • Without local, variables are global by default

Key Takeaways

Use local inside functions to limit variable scope and avoid conflicts.
Local variables do not affect or overwrite global variables with the same name.
Declaring variables without local inside functions makes them global.
The local keyword only works inside functions, not in the global scope.
Always use local to keep your bash scripts clean and avoid unexpected bugs.