ex63.sh

来自「Shall高级编程」· Shell 代码 · 共 53 行

SH
53
字号
#!/bin/bash#               factorial#               ---------# Does bash permit recursion?# Well, yes, but...# It's so slow that you gotta have rocks in your head to try it.MAX_ARG=5E_WRONG_ARGS=65E_RANGE_ERR=66if [ -z "$1" ]then  echo "Usage: `basename $0` number"  exit $E_WRONG_ARGSfiif [ "$1" -gt $MAX_ARG ]then  echo "Out of range (5 is maximum)."  #  Let's get real now.  #  If you want greater range than this,  #+ rewrite it in a Real Programming Language.  exit $E_RANGE_ERRfi  fact (){  local number=$1  #  Variable "number" must be declared as local,  #+ otherwise this doesn't work.  if [ "$number" -eq 0 ]  then    factorial=1    # Factorial of 0 = 1.  else    let "decrnum = number - 1"    fact $decrnum  # Recursive function call (the function calls itself).    let "factorial = $number * $?"  fi  return $factorial}fact $1echo "Factorial of $1 is $?."exit 0

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?