Frequently Asked Question
How do shell functions work and what does the local keyword do?
A bash function is a named block of code defined as name() { ...; } and called by just
writing its name, like a regular command. Inside the function, $1`, `$2, $@, and
$# refer to the function's own arguments, not the script's, which is one of the
occasional surprises. A function's "return value" is its exit code (0–255, set with
return N); to return data, write it to standard output and capture it with command
substitution: result=$(my_function arg1).
By default, every variable assigned inside a function is global, visible everywhere in
the script, mutating outer state. That is almost always wrong. The local keyword
confines a variable to the function: local count=0 creates a fresh count that
vanishes when the function returns, even if there is a count in the enclosing scope.
Use local for every variable you assign inside a function, by reflex, unless you
genuinely intend to mutate global state. It is the difference between a function that
composes cleanly and one that breaks the next caller for mysterious reasons.