Designing Functions with Local Scope and Return Codes
Write functions that use local variables, exit statuses, and printf-based return values instead of fragile globals.
Why Function Scope Matters
In Bash, variables are global by default. A variable set inside a function leaks out into the caller's scope unless you explicitly declare it local. This is a common source of subtle bugs in shell scripts.
- Functions without
localcan silently overwrite caller variables. localvariables are destroyed when the function returns.- Clean scope boundaries make functions reusable and testable in isolation.
This lesson teaches you to write functions that are self-contained: they use local variables, communicate results through exit codes and printf, and never rely on implicit global state.
The Global Leak Problem
Here is a concrete example of a global variable leak. The function set_name sets a variable called result, which quietly overwrites the caller's own result variable.
Run this script and observe the unexpected output — the caller's result is gone after the function call.
#!/usr/bin/env bash
set_name() {
result="Alice" # No 'local' — this is GLOBAL
}
result="important data"
echo "Before: $result"
set_name
echo "After: $result" # Prints 'Alice', not 'important data'All lessons in this course
- Designing Functions with Local Scope and Return Codes
- Building and Sourcing Reusable Bash Libraries
- Parsing Flags and Arguments with getopts
- Passing Arrays and Associative Maps Between Functions