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

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:

  1. Recursive Functions
Syntax
bash
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

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)"
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
  1. Forgetting a base case, which makes endless recursion until the shell fails.
  2. Not using local for variables, so the recursive calls overwrite each other's values.
  3. Expecting deep recursion to be fast, when Bash functions are slow and limited in depth.

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.