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