← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 9 of 13

Recursive Functions

In this page:

  1. Recursive Functions

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

bash
#!/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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.