I want to do a function that will return the factorial of a number in bash
Here’s the current code that doesn’t work, can anyone tell me what’s wrong and how to correct it? I just started learning bash and I don’t know that much.
#!/bash/bin
factorial()
{
let n=$1
if (( "$n" <= "1" ))
then return 1
else
factorial n-1
return $n*$?
fi
return 0
}
factorial 5
echo "factorial 5 = $?"
There are several syntax and a quite obvious logic one (return 0)
A working version is below:
You are missing:
return is bad (should use
echo)shbang line (is /bin/bash not /bash/bin)
Can’t do arithmetic outside of
(( ))or$(( ))(orlet, but(( ))is preferred)