第六章 shell函数

1.定义函数
funcation name()
{
   command1
   ....
}

函数名()
   {
   command1
   ...
   }
eg.

#!/bin/bash
#hellofun
function hello()
{
echo "hello,today is `date`"
return 1
}

2.函数调用
#!/bin/bash
#hellofun
function hello()
{
echo "hello,today is `date`"
return 1
}
echo "now going to the function hello"
hello
echo "back from the function"

所以调用函数只需要在脚本中使用函数名就可以了。

3.参数传递
像函数传递参数就像在脚本中使用位置变量$1,$2...$9

4.函数文件
函数可以文件保存。在调用时使用". 函数文件名"(.+空格+函数文件名)
如:
hellofun.sh
#!/bin/bash
#hellofun
function hello()
{
echo "hello,today is `date`"
return 1
}

func.sh
#!/bin/bash
#func
. hellofun.sh
echo "now going to the function hello"
echo "Enter yourname:"
read name
hello $name
echo "back from the function"

[test@szbirdora 1]$ sh func.sh
now going to the function hello
Enter yourname:
hh
hello,hh today is Thu Mar 6 15:59:38 CST 2008
back from the function

5.检查载入函数 set
删除载入函数 unset 函数名

6.函数返回状态值 return 0、return 1

7.脚本参数的传递
shift命令
shift n 每次将参数位置向左偏移n

#!/bin/bash
#opt2
usage()
{
echo "usage:`basename $0` filename"
}
totalline=0
if [ $# -lt 2 ];then
    usage
fi
while [$# -ne 0]
do
    line=`cat $1|wc -l`
    echo "$1 : ${line}"
    totalline=$[$totalline+$line]
    shift                               #   $# -1
done
echo "-----"
echo "total:${totalline}"

[test@szbirdora 1]$ sh opt2.sh myfile df.out
myfile : 10
df.out : 4
-----
total:14


8.getopts命令
获得多个命令行参数
getopts ahfvc OPTION   --从ahfvc一个一个读出赋值给OPTION.如果参数带有:则把变量赋值给:前的参数--:只能放在末尾。
该命令可以做获得命令的参数
#!/bin/bash
#optgets
ALL=false
HELP=false
FILE=false
while getopts ahf OPTION
do
   case $OPTION in
    a)
      ALL=true
      echo "ALL is $ALL"
      ;;
    h)
      HELP=true
      echo "HELP is $HELP"
      ;;
    f)
      FILE=true
      echo "FILE is $FILE"
      ;;
    \?)
      echo "`basename $0` -[a h f] file"
      ;;
    esac
done

[test@szbirdora 1]$ sh optgets.sh -a -h -m
ALL is true
HELP is true
optgets.sh: illegal option -- m
optgets.sh -[a h f] file

getopts表达式:
while getopts p1p2p3... var
   do
    case var in
    ..)
    ....
   esac
done
如果在参数后面还需要跟自己的参数,则需要在参数后加:
如果在参数前面加:表示不想将错误输出
getopts函数自带两个跟踪参数的变量:optind,optarg
optind初始值为1,在optgets处理完一次命令行参数后加1
optarg包含合法参数的值,即带:的参数后跟的参数值