In the following example, we will create a function to compute number’s factorial result.
Let’s echo in the function to support fetch return value outside.

#! /usr/bin/bash

set -e
if [ -z "$1" ]; then
    echo "Usage: `basename $0` number"
    exit 1
fi

#define a function factorial
fact ()
{
    value=$1
    if [ $value -eq 1 ]; then
        result=1
    else
        para=$(expr $value - 1)
        rest=$(fact $para)
        result=$(expr $value \* $rest)
    fi

    echo $result
}

myValue=$( fact $1 )
echo "result is $myValue"

Output:

➜  shellLib git:(master) ✗ ./recurse.sh 6
result is 720
Categories: Shell

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

E-book Converter
: help you to convert E-book.

X
A prohibited operation
0
Would love your thoughts, please comment.x
()
x