Recursive Functions
A recursive function is like standing between two mirrors, or a set of Russian nesting dolls: each call opens a smaller one until it reaches the tiniest doll, which is the stopping point.
In this page:
Syntax
function_name() {
if [ base_case ]; then
return
fi
function_name arguments
}
Recursive Functions
A Bash function can call itself, producing recursion just like in any other language, as long as there's a base case that stops the recursion.
Each recursive call runs in the same shell but with its own set of local variables. Bash has no built-in recursion depth limit protection beyond the system stack, so deep recursion can be risky.
Note:
Always define a clear base case first — without one, a recursive Bash function will run until it crashes.
Example: Recursive Functions
#!/bin/bash
factorial() {
local n=$1
if (( n <= 1 )); then
echo 1
else
local prev=$(factorial $((n - 1)))
echo $(( n * prev ))
fi
}
echo "5! = $(factorial 5)"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting a base case, which makes endless recursion until the shell fails.
- Not using
localfor variables, so the recursive calls overwrite each other's values. - Expecting deep recursion to be fast, when Bash functions are slow and limited in depth.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null