Recursive functions

A recursive function is a function that calls itself from inside itself. This function is very useful when you need to call the function to do something again from inside of it. The most famous example for that is calculating factorials.

To calculate the factorial of 4, you multiply the number by the descending numbers. You can do it like this:

4! = 4*3*2*1

The ! sign means factorial.

Let's write a recursive function that calculates the factorial of any given number:

#!/bin/bash 
calc_factorial() { 
if [ $1 -eq 1 ] 
then 
echo 1 
else 
local var=$(( $1 - 1 )) 
local res=$(calc_factorial $var) 
echo $(( $res * $1 )) 
fi 
} 
  
read -p "Enter a number: " val 
factorial=$(calc_factorial $val) 
echo "The factorial of $val is: $factorial" 

First, we define the function which is called calc_factorial and inside it we check if the number equals 1 and if so, the function will return 1 because the factorial of 1 equals 1.

Then we decrement the number by one and call the function from inside it and that will call the function again.

This will continue to happen until it reaches 1 and then the function will exit.