fac() { { echo 1; seq $1; } | paste -s -d\* | bc; }
This one-liner defines a shell function named fac
that computes the factorial of a positive integer. Once this function has been defined (you can put it in your .bashrc
), you can use it as follows:
$ fac 10
3628800
Let's break the function down. Assume that we want to compute the factorial of 4. First, it echo
's 1, so that the factorial of 0 works correctly (because seq 0
outputs nothing). Then, seq
is used to generate a list of numbers:
$ echo 1; seq 4
1
1
2
3
4
We want to combine these numbers into a multiplication expression 1*1*2*3*4
. In other words, we want to paste these lines together with a *
in between. We can do this using the paste
command. To pass the output of both the echo
and seq
, we group the commands together using the { ...; }
syntax:
$ { echo 1; seq 4; } | paste -s -d\*
1*1*2*3*4
Finally, we pass this expression to bc
to actually compute it:
$ { echo 1; seq 4; } | paste -s -d\* | bc
24
The $1
in the function means "the first argument", making the function usable with any positive integer parameter.
factorial() ( IFS=\*; let N=$1-1 k="$*" && factorial "$N" "$k" || echo ${2-1} )