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