Question
How to write a factorial function recursivly ?
• A recursive function is a function that repeatedly calls itself.
• No limit is placed on the number of recursive calls.
• Create a shell script called fact.sh:
 #!/bin/bash
# fact.sh - Shell script to to find factorial of given command line arg
factorial () {
local i = $1 local f declare -i i declare -i f # factorial() is called until the value of$f is returned and is it is <= 2
# This is called the recursion
[ $i -le 2 ] && echo$i || { f = $(( i - 1 )) f =$( factorial $f ) f =$(( f * i ))
echo $f ; } } # display usage [$# -eq 0 ] && { echo "Usage: $0 number" ; exit 1 ; } # call factorial factorial$1 

Save and close the file. Run it as follows:

 chmod +x fact.sh
./fact.sh
./fact.sh 2 ./fact.sh 5 

Question
How to write a factorial function recursivly ?
?

Question
How to write a factorial function recursivly ?
• A recursive function is a function that repeatedly calls itself.
• No limit is placed on the number of recursive calls.
• Create a shell script called fact.sh:
 #!/bin/bash
# fact.sh - Shell script to to find factorial of given command line arg
factorial () {
local i = $1 local f declare -i i declare -i f # factorial() is called until the value of$f is returned and is it is <= 2
# This is called the recursion
[ $i -le 2 ] && echo$i || { f = $(( i - 1 )) f =$( factorial $f ) f =$(( f * i ))
echo $f ; } } # display usage [$# -eq 0 ] && { echo "Usage: $0 number" ; exit 1 ; } # call factorial factorial$1 

Save and close the file. Run it as follows:

 chmod +x fact.sh
./fact.sh
./fact.sh 2 ./fact.sh 5 
If you want to change selection, open document below and click on "Move attachment"

Recursive function - Linux Shell Scripting Tutorial - A Beginner's handbook
- A Beginner's handbook Recursive function From Linux Shell Scripting Tutorial - A Beginner's handbook Jump to navigation Jump to search ← Source command Home Putting functions in background → <span>A recursive function is a function that repeatedly calls itself. No limit is placed on the number of recursive calls. Create a shell script called fact.sh: #!/bin/bash # fact.sh - Shell script to to find factorial of given command line arg factorial(){ local i=$1 local f declare -i i declare -i f # factorial() is called until the value of$f is returned and is it is <= 2 # This is called the recursion [ $i -le 2 ] && echo$i || { f=$(( i - 1)); f=$(factorial $f); f=$(( f * i )); echo $f; } } # display usage [$# -eq 0 ] && { echo "Usage: $0 number"; exit 1; } # call factorial factorial$1 Save and close the file. Run it as follows: chmod +x fact.sh ./fact.sh ./fact.sh 2 ./fact.sh 5 Sample outputs: 2 120 You can debug the script as follows: bash -x ./fact.sh 5 Sample outputs: + '[' 1 -eq 0 ']' + factorial 5 + local i=5 + local f + declare -i i + declare -i f + [[ 5

#### Summary

status measured difficulty not learned 37% [default] 0

No repetitions