0
0
Bash Scriptingscripting~5 mins

Local variables (local keyword) in Bash Scripting

Choose your learning style9 modes available
Introduction
Local variables help keep data inside a function so it doesn't affect the rest of the script.
When you want to use a variable only inside a function without changing variables outside.
When writing functions that run multiple times and need fresh variables each time.
When avoiding accidental changes to variables used elsewhere in the script.
Syntax
Bash Scripting
local variable_name=value
Use 'local' inside a function to create a variable that only exists in that function.
Local variables disappear when the function ends.
Examples
Creates a local variable 'count' inside the function.
Bash Scripting
my_function() {
  local count=5
  echo "Count is $count"
}
Local variable 'name' holds a string inside the function.
Bash Scripting
my_function() {
  local name="Alice"
  echo "Hello, $name"
}
Declares a local variable first, then assigns a value.
Bash Scripting
my_function() {
  local number
  number=10
  echo $number
}
Sample Program
Shows how 'local' keeps the variable 'count' inside the function separate from the outside 'count'.
Bash Scripting
#!/bin/bash

count=100

define_function() {
  local count=5
  echo "Inside function, count = $count"
}

echo "Before function, count = $count"
define_function
echo "After function, count = $count"
OutputSuccess
Important Notes
Without 'local', variables inside functions can change variables outside, causing bugs.
Local variables help make functions safer and easier to understand.
Summary
Local variables exist only inside functions.
Use 'local' keyword to declare them.
They prevent accidental changes to variables outside the function.