函数语法案例1
一、rsync启停脚本(函数)
1) 脚本
cat /server/scripts/b6.sh
#!/bin/sh
. /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
#!/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
}
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.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
#!/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. [失败]
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步