Local Variables
A local variable is like a whiteboard that gets wiped when a meeting ends. Its value only lives inside the function and cannot mess up labels used elsewhere.
In this page:
Syntax
function_name() {
local variable_name=value
}
Local Variables
By default, variables set inside a function are global and can clash with variables outside it.
The local keyword scopes a variable to just that function call, preventing it from leaking into or overwriting the caller's variables. Using local for anything that isn't meant to be shared is good practice.
Warning:
Without
local, a variable assigned inside a function silently overwrites any same-named global variable.Example: Local Variables
#!/bin/bash
message="global value"
show_message() {
local message="local value"
echo "Inside function: $message"
}
show_message
echo "Outside function: $message"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
local, so variables leak into the global scope. - Using
local x=$(cmd)and losing the exit status ofcmd. - Expecting
localto work outside a function, which gives an error.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null