ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # **函数语法案例1** ## **一、rsync启停脚本(函数)** ### 1) 脚本 * `cat /server/scripts/b6.sh ` ```shell #!/bin/sh # chkconfig: 2345 20 80 # description:rsyncd start up scripts by noah. . /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|wc -l` -ge 1 ] then action "rsyncd is started." /bin/true else action "rsyncd is started." /bin/false fi } function stop () { pkill rsync &>/dev/null sleep 2 if [ `netstat -lntup|grep rsync|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 2 start else usage fi } main $* ``` ### 2) 执行结果: > * `sh /server/scripts/b6.sh stop` rsyncd is stopped. [确定] > * `sh /server/scripts/b6.sh start` Failed to parse config file: /etc/rsyncd.conf rsyncd is started. [失败] # **函数语法案例2** ## **一、函数传参测试网址异常** ### 1. 基本实现 #### 1) 代码 * `cat /server/scripts/b5.sh ` ```shell #!/bin/bash function usage () { echo "usage:$0 input one url" exit 1 } #错误提示函数 function check_url () { wget --spider -q -o /dev/null --tries=1 -T 5 $1 if [ $? -eq 0 ] then echo "$1 is yes." else echo "$1 is no." fi } #url测试函数,注意$1 function main () { if [ $# -ne 1 ] then usage fi check_url $1 } #主函数,先判断参数个数,不符合要求调用错误提示函数提示,符合要求的话,调用check_url函数并把$1传递给函数 main $* #这是将命令行接受到的所有参数,作为函数参数传递给函数内部的一种常用手法 ``` #### 2) 执行情况 > * `sh /server/scripts/b5.sh www.baidu.com` www.baidu.com is yes. > * `sh /server/scripts/b5.sh www.baidu.co` www.baidu.co is no. > * `sh /server/scripts/b5.sh www.baidu.com abc.com` usage:/server/scripts/b5.sh input one url ### 2. 改为命令行传参 #### 1) 脚本 * `cat /server/scripts/b5.sh ` ```shell #!/bin/bash [ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1 function usage () { echo "usage:$0 input one url" exit 1 } function check_url () { wget --spider -q -o /dev/null --tries=1 -T 5 $1 if [ $? -eq 0 ] then action "$1 is yes." /bin/true else action "$1 is no." /bin/false fi } function main () { if [ $# -ne 1 ] then usage fi check_url $1 } main $* ``` #### 2) 执行结果 > * `sh /server/scripts/b5.sh www.baidu.com ` www.baidu.com is yes. [确定] > * `sh /server/scripts/b5.sh www.baidu.co` www.baidu.co is no. [失败]