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 c
There are several syntax and a quite obvious logic one (return 0)
A working version is below:
#!/bin/bash
factorial()
{
if (( $1 <= 1 )); then
echo 1
else
last=$(factorial $(( $1 - 1 )))
echo $(( $1 * last ))
fi
}
factorial 5
You are missing:
return is bad (should use echo
)
shbang line (is /bin/bash not /bash/bin)
Can't do arithmetic outside of (( ))
or $(( ))
(or let
, but (( ))
is preferred)