Shell脚本中的递归函数以及遍历目录

Linux大全评论1.6K views阅读模式

1 实现递归函数算阶乘:

#!/bin/bash
#fileName:function2.sh
factorial()
{
local i=$1;    #需要使用local关键字,否则返回结果始终为0,因为shell将默认的变量当作全局变量
if [ $i -eq 0 ]
then
  rtn=1
else
  factorial `expr $i - 1`
   #echo $rtn
  rtn=`expr $i "*" $rtn` #可以使用return `expr $i /* $?`,但是当结果大于256时,结果出错,因为shell定义的$?范围限制
fi
  return $rtn;
}
if [ -z $1 ]
 then
  echo "need one parameter";
  exit 1;
fi

factorial $1;
echo $rtn;

企鹅博客
  • 本文由 发表于 2019年9月28日 10:55:15
  • 转载请务必保留本文链接:https://www.qieseo.com/175891.html

发表评论