cxg518 发表于 2018-8-29 09:03:24

shell学习之函数与库(一)

  函数堪称shell的精华,有了函数和库,shell处理复杂问题也像编译语言那样有头有脸了,总之,shell的函数和库的重要性不言而喻。
  1   函数的定义
  建议使用
  FUNC_NAME (){}的定义方法
  有些人可能喜欢在前面加上function标记,这是bash独有的
  function FUNC_NAME(){}
  有点是简洁,容易识别是函数
  2函数返回值
  一般可以用
  ①在函数中,return 返回
  ②调用函数,通过命令引用 比如   a=`func_name   haha`
  3 书上的一个小例子,计算1-6的二次方,三次方
  # cat square-cube.sh
  #!/bin/bash
  #
  txt="_mktmp"
  square_cube()
  {
  echo "$2 * $2"|bc > $1
  echo "$2 * $2 * $2"|bc >> $1
  }
  for i in `seq 1 5`
  do
  square_cube $txt $i
  square=`head -1 $txt`
  cube=`tail -1 $txt`
  echo "square of $iis $square"
  echo "cube   of $iis $cube"
  done
  rm -f $txt
  执行结果:
  # ./square-cube.sh
  square of 1is 1
  cube   of 1is 1
  square of 2is 4
  cube   of 2is 8
  square of 3is 9
  cube   of 3is 27
  square of 4is 16
  cube   of 4is 64
  square of 5is 25
  cube   of 5is 125
  总结下:这里是一个很简单的函数调用,函数的功能就是处理办理计算结果保存在特定位置,主脚本负责控制流程
  tips:1和l很相似,大家要注意,害的我浪费了时间
  4debugger脚本
  # cat debugger.sh
  #!/bin/bash
  #
  #this a debugger by function
  LOGFILE=/tmp/log.log
  #指定脚本名
  APPNAME=$0
  #指定DEBUG级别,越高就显示越多的冗余信息
  VERBOSE=10
  #logmsg负责显示传递给它的消息
  logmsg()
  {
  echo "$APPNAME:`date`--entered---$@" >> $LOGFILE
  }
  #debug负责显示错误/调试 信息
  debug()
  {
  verbosity=$1
  #shift的目的在于把级别挪走,以便只显示debug信息
  shift
  if [ "$verbosity" -le "$VERBOSE" ] ;then
  echo "$APPNAME:`date`---level:${verbosity}---:$@" >> $LOGFILE
  fi
  }
  #die函数你懂得
  die(){
  echo "$APPNAME:`date`----fatal error--$@"
  exit 1
  }
  #主脚本测试
  #显示脚本开始,好像有点多余哈
  logmsg   nowthe log-checkingsystem start -------
  #测试uname -a命令是否存在
  uname -a||die uname -a commandnot find.
  #uname存在的话,继续执行
  logmsg -----------system-info`uname -a`
  #判断是redhat或者debian系统
  cat /etc/redhat-release||debug 8 this is not a redhat system!
  cat /etc/debian-release||debug 8this is not a debian system!
  #书上更多点,我这里省略了一些,为了简洁
  运行结果
  # ./debugger.sh
  Linux www.centos.vbird 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

  CentOS>  cat: /etc/debian-release: No such file or directory
  总结下,这里三个函数互相协调使用,有撤销的,有报错的,注意$@指全部参数,$0指文件名,$1指第一个参数,等,这些如果不知道的话得恶补啦
  5 递归函数举例
  典型a:计算阶乘
  # cat factorial.sh
  #!/bin/bash
  #
  factorial(){
  if [ "$1" -gt "1" ];then
  previous=`expr $1 - 1`
  parent=`factorial $previous`
  result=`expr $1 \* $parent`
  echo $result
  else
  echo 1
  fi
  }
  factorial $1
  执行结果:
  # sh -x factorial.sh3
  + factorial 3
  + '[' 3 -gt 1 ']'       ;;判断是否是1
  ++ expr 3 - 1
  + previous=2
  ++ factorial 2   ;;由于parent=`factorial $previous`在函数中调用了该函数,所以是递归
  ++ '[' 2 -gt 1 ']'
  +++ expr 2 - 1
  ++ previous=1
  +++ factorial 1
  +++ '[' 1 -gt 1 ']'
  +++ echo 1
  ++ parent=1   ;;最后知道初始条件为1的阶乘为1
  +++ expr 2 '*' 1
  ++ result=2
  ++ echo 2
  + parent=2
  ++ expr 3 '*' 2
  + result=6
  + echo 6
  6
  可以算大的数,就是慢…

页: [1]
查看完整版本: shell学习之函数与库(一)