shell函数:
定义函数
函数调用
参数传递
函数文件
载入和删除函数
函数返回状态
定义:
shell允许将一组命令或语句形成一个可用快,这些快称为shell函数
定义函数的格式为:
函数名()
{
命令1
。。。。。。。
}
for example:
#!/bin/bash
#hellofun
function hello()
{
echo "Hello ,today is `date`"
return 1
}
echo "now going to the unction hello"
hello --调用函数名即可
echo "back from the function"
参数传递:
#!/bin/bash
#hellofun
function hello()
{
echo "Hello , $1 today is `date`"
return 1
}
echo "now going to the unction hello"
hello chinaitlab --调用函数名即可
echo "back from the function"
函数文件:
#!/bin/bash
#hellofun
#Source function
.hellofun
#set --可以看到函数是否载入
unset hello-卸载hello函数
echo "now going to the unction hello"
hello
echo "back from the function"
hellofun源代码:
#!/bin/bash
#hellofun
function hello()
{
echo "Hello ,today is `date`"
return 0 返回1代表错误
}
#!/bin/bash
#func
echo "now going to the unction hello"
hello
echo $?--返回的状态值用$?来表示
echo "back from the function"
第七章 脚本参数传递
shift 命令
getopts
每次将参数位置向左偏移n位
#!/bin/bash
#opt2
usage()
{
echo "usage:`basename $0` filenames"
}
totalline=0
if[$# -lt 2];then $# :参数的个数
usage
fi
while[$# -ne 0]
do
line=`cat $1|wc -l`
echo "$1:${line}"
totalline=$[$totalline+$line]
shift
done
echo "------------"
echo "total:${totalline}"
位置变量可以超过9个,自己验证
getopts
获得多个命令行参数。
#!/bin/bash
ALL=false
HELP=false
FILE=false
VERBOSE=false
while getopts ahfvc 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"
;;
v)
VERBOSE=true
echo "VERBOSE is $VERBOSE"
;;
c)
echo "c value is $c"
;;
/?)
echo "`basename $0` -[a h f v ] -[c value] file"
;;
esac
done