Function Scope
Bash variables are global by default. Use local within functions to contain changes and prevent accidental side effects.
Local vs Global
Declare a variable with local inside a function to keep it scoped. Without local, assignments modify the global variable.
Output
Click Run to execute your code
Note:
export makes variables available to child processes. It does not make them local.
Pro Tip: Use a consistent prefix for globals (e.g.,
APP_) and always declare temporaries with local inside functions.
Caution: Sourcing files (
. file.sh) executes in the current shell and can override globals; keep sourced files tidy and namespaced.
Common Mistakes
1) Accidental global mutation
# Wrong
count=0
inc() { count=$((count+1)); }
inc; echo "$count" # modified globally
# Correct
inc() { local count=0; count=$((count+1)); echo "$count"; }
echo "local: $(inc)"; echo "global: $count"
2) Assuming export makes a variable local
# Wrong
foo=bar; export foo # Still global in current shell
# Correct
local foo=bar # scoped to function only
export APP_TOKEN # only for children
Exercise: Safe Increment
Task: Implement safe_inc that increments a number passed by value and echoes the result without changing any global counter variable.
- Do not modify globals.
- Return non-zero if the input is not an integer.
Output
Click Run to execute your code
Show Solution
safe_inc() {
local n=$1
[[ $n =~ ^-?[0-9]+$ ]] || return 1
echo $(( n + 1 ))
}
counter=41
safe_inc "$counter" # echoes 42
echo "$counter" # unchanged
Summary
- Variables are global unless declared
localin a function. - Shadowing lets you reuse names safely with
local. - Use
exportto pass values to child processes, not for scoping.
What's Next?
Finally, build recursive functions for problems like factorial and directory traversal in Recursive Functions.
Enjoying these tutorials?