Home > Software engineering >  Bash recursive function not executing properly
Bash recursive function not executing properly

Time:10-26

I have a simple factorial recursive function defined here. it works okay until num=5 but later on, it starts giving garbage values. I'm reading the num from the user and then feeding it into the recursive function. I'm not able to figure out the issue as I'm new to the arithmetic side of bash.

function fact {
    if (( $1==1 ))
    then
        return 1
    else
        prev=$(( $1-1 ))
        fact $prev
        prev_fact=$?
        this_fact=$( expr $1 \* $prev_fact )
        # this_fact=$(( $1 * $prev_fact )) This also works the same way as above
        return $this_fact
    fi
}

echo -n "Enter the number: "
read num
fact $num
val=$?
echo "Factorial of "$num" is "$val""

CodePudding user response:

Return codes are limited to the range 0-255. That's bad news for ol' fact here because anything larger than 5! = 120 will overflow.

Return codes are intended to be used to signal success and failure, not for general integer data. To "return" a value from a function you should instead echo it to stdout and use $(...) in the caller to capture it.

function fact {
    if (($1 == 1))
    then
        echo 1
    else
        prev=$(($1 - 1))
        prev_fact=$(fact "$prev")
        echo $(($1 * prev_fact))
    fi
}

CodePudding user response:

Or just use this variable $var to store/print data

fact(){
    (($1 > 1)) && {
         local prev=$(($1 - 1))
         fact $prev
         val=$(($1 * $val))
    } || val=1
}

read -p "Enter the number: " num
fact $num
echo "Factorial of '$num' is '$val'"
  • Related