A recursive function is a function which calls itself more times. It can be useful for example when it's necessary to repeat many times the same operation on data. Here there's an example, based on the Euclid's algorithm for computing the greatest common divisor between two numbers M and N. The algorithm has this structure:
if [ N = 0 ]
M is the GCD
else
compute the remainder R of M/N
if [ R = 0 ]
GCD = R
else
exchange M and N
repeat from beginning
fi
fi
and it can be implemented with this script:
#!/bin/bash
# Exit variables
EXIT_SUCCESS=0
EXIT_FAILURE=1
usage()
{
echo
echo "Function usage:"
echo "$(basename $0) <first number> <second number>"
echo
exit $EXIT_FAILURE
}
mcd ()
{
# It sets as new m and n the values passed by the last call
m=$1
n=$2
# It verifies that m and n are valid, or that
# the end of the algorithm was not reached
if [ $n -eq 0 -a $m -eq 0 ]; then
echo "gcd(0,0) is not defined!"
exit $EXIT_FAILURE
elif [ $m -eq 0 ]; then
return $n
elif [ $n -eq 0 ]; then
return $m
fi
# Recursive call of the function
# The first parameter is the residue of $n / $m,
# The second parameter is $m
# the third parameter is $n
# Note how $m and $n are continuously inverted
mcd $(( $n % $m )) $m
}
################
# Main Program #
################
# Security control: if the number of passed values
# is not 2, it shows the usage of this script
if [ $# -ne 2 ]; then
usage
fi
# It calls the function mcs, and it passes it as parameters
# the values written at the command line when the script
# was launched
mcd $1 $2
# It prints the results
MCD=$?
echo "The gcd of \"$1\" and \"$2\" is: $MCD"
exit $EXIT_SUCCESS