local variable
A variable that exists only inside one function call and cannot be seen or changed from outside it.
In more detail
Local variables disappear when the call ends, and two functions can use the same local name without interfering. Languages differ in how a variable becomes local: in Python any name assigned inside a function is local, while in Bash you must declare it with the local keyword. Without local, a Bash function writes to the script's global variables.
Example
work() { local result="success"; echo "$result"; }Related terms
- global variable — A variable defined at the top level of a program or module, shared by all the code in that process.
- dynamic scoping — Bash's rule that a function can see the local variables of whichever function called it, not only globals.
- shell function — A named group of commands, defined as name() { ...; }, that you then run like any other command.
- declare — The bash builtin that creates variables with attributes: -i integer, -r read-only, -a array, -A associative array, -n name reference, and -p to print.
- scope — The region of a program where a name can be seen and used.
- parameter — A name in a function definition that receives the value of an argument each time the function is called.
- NameError — The exception raised when code uses a name that has not been assigned, or is misspelt, or is not visible from here.
Taught in
- Functions, local And declare — Bash Scripting & Command Line Automation
- set -e, set -u And pipefail: Promises And Traps — Bash Scripting & Command Line Automation
- Debugging: set -x, bash -n And Reading The Error — Bash Scripting & Command Line Automation
- Style That Prevents Bugs — Bash Scripting & Command Line Automation
- POSIX sh Versus Bash — Bash Scripting & Command Line Automation
- eval, And What To Use Instead — Bash Scripting & Command Line Automation
- The String Format Method — Hands-on Python: Complete Video Course & Book
- Returning Values — Hands-on Python: Complete Video Course & Book
- Local Scope And Global Constants — Hands-on Python: Complete Video Course & Book
- Dictionaries And String Formatting — Hands-on Python: Complete Video Course & Book
- Chapter One In One Sitting — Hands-on Python: Complete Video Course & Book
- Functions, Return Values And Recursion — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Parameters, Arguments And Scope — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Functions And Exceptions Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Generators And Iterators — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Closures: Functions That Remember — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
References
- Bash Reference Manual: Bash Builtins (local)
- Bash Reference Manual: Shell Functions
- Python tutorial: defining functions
- Execution model: naming and binding