Debian Codegraph @

ex63.sh

raw symbols SCIP
1 #!/bin/bash
2
3 # factorial
4 # ---------
5
6
7 # Does bash permit recursion?
8 # Well, yes, but...
9 # It's so slow that you gotta have rocks in your head to try it.
10
11
12 MAX_ARG=5
13 E_WRONG_ARGS=85
14 E_RANGE_ERR=86
15
16
17 if [ -z "$1" ]
18 then
19 echo "Usage: `basename $0` number"
20 exit $E_WRONG_ARGS
21 fi
22
23 if [ "$1" -gt $MAX_ARG ]
24 then
25 echo "Out of range ($MAX_ARG is maximum)."
26 # Let's get real now.
27 # If you want greater range than this,
28 #+ rewrite it in a Real Programming Language.
29 exit $E_RANGE_ERR
30 fi
31
32 fact ()
33 {
34 local number=$1
35 # Variable "number" must be declared as local,
36 #+ otherwise this doesn't work.
37 if [ "$number" -eq 0 ]
38 then
39 factorial=1 # Factorial of 0 = 1.
40 else
41 let "decrnum = number - 1"
42 fact $decrnum # Recursive function call (the function calls itself).
43 let "factorial = $number * $?"
44 fi
45
46 return $factorial
47 }
48
49 fact $1
50 echo "Factorial of $1 is $?."
51
52 exit 0