第九章 函数

来源:互联网 发布:淘宝一年前的购买记录 编辑:程序博客网 时间:2024/05/30 23:46

1、函数的定义和使用

usage()                                 

{                                                      

}                                                      

function usage ()

{


}

使用  if   ...            usage      fi    \

2、检查函数定义与取消

(1)、在shell中输入:

$ run()

>{

>df -h

> }

(2)、declare -f run   //查看定义

run

{

df -h

}

(3)、$ run   //运行函数

(4)、unset run   //取消定义

3、定义返回为任意数和字符串的函数

eg:

proc()

{

if [ $# -eq 1 ]

then

echo "hello $1"

fi

}

OUT=`proc "mlkk"`

echo "$OUT"

exit                       

输出:   hello mlkk

4、变量的作用域

(1)、函数体内定义变量时,如无local关键字,则其为全局变量

(2)、函数体内定义局部变量时需要加local

5、库函数的使用

(1)、库的建立

library.lib            //库文件后缀可以随意

#!/bin/echo  Warning:this is a library which should be sourced!

test_platform()

{

  return 0

}

(2)、建立shell脚本

lib.sh

#!/bin/bash

source ./library.lib

test_platform

exit0