Q:

Why does my bash function return the wrong value?

fact() 
{
    if [ $1 -eq 1 ]
    then
        return 1
    else
        y=`expr $1 - 1`
        fact $y
        b=$(($1 * $?))
        return $b
    fi
}
echo "enter"
read n
fact $n
echo "$?"

This is a program to find the factorial of a number. The output is correct up to 5. The output of 6 is giving as 208 but the correct answer is 720. What's causing this error?

A:

Function return values can only go up to 255:
a()
{
        return 255
}

a
echo $?

b()
{
        return 256
}

b
echo $?

Produces:
$ bash x.sh
255
0

return is like exit and exit can only take values up to 255 (http://www.unix.org/whitepapers/shdiffs.html).
One alternative is to switch to an iterative suggestion, as described in another answer.
Alternatively you can use echo and capture the recursive output that way:
#!/bin/bash

fact() 
{
    if [ $1 -eq 1 ]
    then
        echo 1
    else
        y=$(expr $1 - 1)
        f=$(fact $y)
        b=$(($1 * $f))
        echo $b
    fi
}
echo "enter"
read n
fact $n

