0

My Original Code:

    # Factorial Using Recursion

    res=1
    fact()
    {
        x=$1
        if [ $x -le 1 ]
        then
            echo "Actual - $res"
            return `expr $res`
        else    
            #echo $x
            res=$(($res * $x))
            echo "($res)"
            fact $[$x-1]                                
        fi
    }
    fact $1
    echo "Factorial of $1 = $?"

The result (stored in $res) is certainly what I want and is also correct. But somehow when it is being returned and caught by $? it becomes erroneous.

Sample Image

1
  • return is not meant to return arbitrary data; it returns an exit status. To return a value, write it to standard output or put it in a global variable. (No, "proper" programming practices are not always applicable in bash.) Commented Oct 8, 2016 at 14:56

1 Answer 1

4

The maximum value of a return code is 255 so there's no way that you can return the factorial of most integers.

Instead, your function should output the value to standard output, e.g. using echo. Capture the output of the function like result=$(fact "$x").

If you want to output other messages while the function is executing then you can print to standard error using echo 'whatever' >&2.

res=1
fact()
{
    x=$1
    if [ "$x" -le 1 ]
    then
        echo "$res"
    else    
        res=$((res * x))
        fact "$((x - 1))"
    fi
}

I've also fixed up your syntax a little bit.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! i'm new to bash :P and hence its just messing with me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.