shell编程(七)

 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值