Local Variables
In this page:
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
🔒
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