第六章 shell函数
1.定义函数
funcation name()
{
command1
....
}
或
函数名()
{
command1
...
}
eg.shell
#!/bin/bash
#hellofun
function hello()
{
echo "hello,today is `date`"
return 1
}bash
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"
因此调用函数只须要在脚本中使用函数名就能够了。ide
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"get
[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 functionit
5.检查载入函数 set
删除载入函数 unset 函数名io
6.函数返回状态值 return 0、return 1function
7.脚本参数的传递
shift命令
shift n 每次将参数位置向左偏移nclass
#!/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包含合法参数的值,即带:的参数后跟的参数值