@yanglt7
2018-10-27T13:45:45.000000Z
字数 2256
阅读 733
Shell
标准写法:
function 函数名 () {
指令...
return n
}
简化写法 1:
function 函数名 {
指令...
return n
}
简化写法 2:
函数名 () {
指令...
return n
}
Shell 的函数分为最基本的函数和可以传参的函数两种,其执行方式分别如下:
1)执行不带参数的函数时,直接输入函数名即可(注意不带小括号)。格式如下:
函数名
2)带参数的函数执行方法,格式如下:
函数名 参数 1 参数 2
cat >>/etc/init.d/functions<<- EOF
ylt(){
echo "I am ylt."
}
EOF
[root@web001 ~]# tail -3 /etc/init.d/functions
ylt(){
echo "I am ylt."
}
#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1
ylt
带参数的 Shell 函数
[root@web001 ~]# tail -3 /etc/init.d/functions
ylt(){
echo "I am ylt. you are $1."
}
#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1
ylt yyy
[root@web001 scripts]# cat rsync1.sh
#!/bin/bash
# checkconfig: 2345 20 80
. /etc/init.d/functions
function usage(){
echo "usage:$0 {start|stop|restart}"
exit 1
}
function start(){
rsync --daemon
sleep 1
if [ `netstat -lntup|grep rsync|grep -v grep|wc -l` -ge 1 ]; then
action "rsyncd is started." /bin/true
else
action "rsyncd is started." /bin/false
fi
}
function stop(){
killall rsync &>/dev/null
sleep 2
if [ `netstat -lntup|grep rsyncd|wc -l` -eq 0 ]; then
action "rsyncd is stopped." /bin/true
else
action "rsyncd is stopped." /bin/false
fi
}
function main(){
if [ $# -ne 1 ]; then
usage
fi
if [ "$1" = "start" ]; then
start
elif [ "$1" = "stop" ]; then
stop
elif [ "$1" = "restart" ]; then
stop
sleep 1
start
else usage
fi
}
main $*
[root@web001 scripts]# sh rsync1.sh start
rsyncd is started. [ OK ]
[root@web001 scripts]# sh rsync1.sh stop
rsyncd is stopped. [ OK ]
[root@web001 scripts]# sh rsync1.sh restart
rsyncd is stopped. [ OK ]
rsyncd is started. [ OK ]
[root@web001 scripts]# sh rsync1.sh s
usage:rsync1.sh {start|stop|restart}