Recursive Functions
In this page:
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
🔒
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