Bounded recursion and reusable helpers
Recursion occurs when a function invokes itself, directly or indirectly. A base case stops recursion; every recursive step must move toward that case. Use a small, validated input and invocation-local variables. Bash does not guarantee tail-call optimization; deep recursion can exhaust resources. FUNCNEST, when set to a positive integer, limits function nesting in Bash, but does not replace input validation or a sound stopping rule. Use a loop for large repetitive tasks. Design helpers with explicit dependencies, input, output and failure contracts. command -v name can check whether a fixed required command is resolvable; it does not prove that the command is trustworthy or the required version. Propagate a failing status instead of printing success afterward. The examples use bounded synthetic values, not arbitrary arithmetic text. The countdown propagates a failed print instead of continuing recursion after a failed output operation. A successful dependency lookup alone does not guarantee a later invocation succeeds.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Bounded countdown
countdown() { [[ $# -eq 1 && $1 =~ ^[0-5]$ ]] || return 2 local n=$1 printf '%s\n' "$n" || return "$?" if (( n == 0 )); then return 0; fi countdown "$(( n - 1 ))"}countdown 3countdown 9printf 'invalid=%s\n' "$?"Expected stdout:
3210invalid=2The single-digit restriction bounds depth and prevents arbitrary arithmetic evaluation.
Check a fixed dependency
need_printf() { command -v printf >/dev/null || return 127 printf '%s\n' ready}need_printfExpected stdout:
readyThe helper reports readiness only if printf is resolvable.
Propagate failure
validate() { return 3; }run_report() { validate || return "$?" printf '%s\n' success}run_reportprintf 'status=%s\n' "$?"Expected stdout:
status=3The success message is skipped and the original failure is preserved.
Common mistakes
A base case alone is insufficient if the next call never approaches it. Do not use unrestricted user input in arithmetic or recursive depth. A dependency check is not a security check.
Practice
Implement a countdown accepting only a single digit from 0 to 5. Show the base case and verify that invalid input produces nonzero status without recursing. Compare the design with a loop.
Next: Function context and introspection