dream789 发表于 2018-8-22 11:25:41

shell脚本从入门到复杂 其八(函数)

  linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。
  Shell的函数存在于内存,而不是硬盘文件,所以速度很快,另外,Shell还能对函数进行预处理,所以函数的启动比脚本更快。
  注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。
  shell中函数的定义格式如下:
  [ function ] funname [()]
  {
  action;
  
  }
  说明:
  1、可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。
  2、参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255
  案例:
  简单的函数调用
  # vi function1.sh
  #!/bin/bash
  demoFun(){
  echo "this is my first function"
  }
  echo "function is starting..."
  demoFun
  echo "function is over"
  执行结果是:
  function is starting...
  this is my first function
  function is over
  返回值
  函数中的关键字“return”可以放到函数体的任意位置,通常用于返回某些值,Shell在执行到return之后,就停止往下执行,返回到主程序的调用行,return的返回值只能是0~256之间的一个整数,返回值将保存到变量“$?”中。
  案例:
  返回两个输入数的和
  # vi .sh function2.sh
  #!/bin/bash
  funreturn(){
  echo "The function is used to add the two figures together..."
  echo "Enter the first number: "
  read num1
  echo "Enter the second number: "
  read num2
  echo "The two number is $num1 and $num2"
  return $(($num1+$num2))
  }
  funreurn
  echo "The sum of the two number is $?"
  执行结果
  # sh function2.sh
  The function is used to add the two figures together...
  Enter the first number:
  4
  Enter the second number:
  5
  The two number is 4 and 5
  The sum of the two number is 9
  参数传递
  在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...
  案例:
  # vi function3.sh
  #!/bin/bash
  funparam(){
  echo "The first param $1"
  echo "The second param $2"
  echo "The ten param ${10}"
  echo "The sum of the param $#"
  echo "Output the all param with string format $*"
  }
  funparam 1 two 3 4 5 6 7 8 9 ak
  执行结果:
  # sh function3.sh
  The first param 1
  The second param two
  The ten param ak
  The sum of the param 10
  Output the all param with string format 1 two 3 4 5 6 7 8 9 ak
  注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。
  补充说明:
参数处理说明$0是脚本本身的名字$#传递到脚本的参数个数$*以一个单字符串显示所有向脚本传递的参数$$脚本运行的当前进程ID号$!后台运行的最后一个进程的ID号$@与$*相同,但是使用时加引号,并在引号中返回每个参数$-显示Shell使用的当前选项,与set命令功能相同$?显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误
页: [1]
查看完整版本: shell脚本从入门到复杂 其八(函数)