Welcome 微信登录

首页 / 操作系统 / Linux / Linux Shell脚本中如何定义函数及调用函数

在代码复用及可维护性方面,函数有着巨大的优势,因此,把常用功能封装成函数是一件非常平常的事。shell脚本中,怎么定义函数及使用函数呢?函数定义:
  1. # func_name 函数名    
  2. function func_name(){  
  3.     #函数体内容  
  4. }  
  5. 或  
  6. # func_name 函数名  
  7. func_name(){  
  8. #函数体内容  
  9. }  
函数调用:func_name parm函数体中,可以通过$1 $2 ...$9接受函数调用中的变量函数可以通过return 返回函数执行的结果可以通过下面一个简单例子,www.linuxidc.com来看下在shell脚本中怎么定义使用函数1、在/root/bin目录下新建函数文件main.funvim /root/bin/main.fun   2、在main.fun文件中编写函数findit内容
  1. #!/bin/sh  
  2. function findit(){          
  3.     if [ $# -lt 1 ] ; then  #判断函数参数个数                 
  4.      echo "Usage: findit filename"                 
  5.      return 1          
  6.     fi        
  7.     for loop #遍历调用函数的参数            
  8.         do  
  9.                     find $HOME -name $loop -print  
  10.             done      
  11.     return 0  
  12. }  
3、Shell中载入函数文件/root/bin/main.fun. /root/bin/main.fun  4、检查载入文件set   set命令将在shell中显示所有的载入函数5、调用函数
  1. findit mysql php #在home 目录查找文件mysql 和文件php