题目:开发启动rsync服务的系统服务脚本
代码:
#!/bin/bash
#Author:cxs
#QQ:981071195
#Time:2020-11-19 18:45:21
#Name:rsync_start.sh
#Version:V1.0
#Description:This is a test script.
. /etc/init.d/functions #引入系统函数库
usage(){ #shell脚本中函数定义的第一种方式
echo $"usage:$0 {start|stop|restart}"
exit 1
}
function st(){ #shell脚本种函数定义的第二年方式,使用"function"声明一个函数
rsync --daemon #让rsync服务进入守护进程模式,相当于开启了rsync服务
sleep 1 #睡眠1秒,让系统对刚刚的操作进行处理
if [ `ps -ef | grep rsync| grep -v grep | wc -l` -gt 0 ];then
action "rsync $1 success!" /bin/true #这里的action就是在脚本开头引入系统函数库后调用的。
else
action "rsync $1 fail!" /bin/false #/bin/true 会在脚本执行成功时显示【OK】;/bin/false 会在脚本执行出错时显示【FAILED】
fi
}
function sp(){
killall rsync &>/dev/null #killall 杀死所有rsync服务相关的进程
sleep 1
if [ `netstat -lntup| grep rsync| grep -v grep | wc -l` -lt 1 ];then
action "rsync $1 success!" /bin/true
else
action "rsync $1 fail!" /bin/false
fi
}
function rt(){
killall rsync &>/dev/null
sleep 1
killpro=`netstat -lntup | grep rsync|wc -l`
rsync --daemon
sleep 1
rsyncpro=`netstat -lntup | grep rsync|wc -l`
if [ "$killpro" -lt 1 -a "$rsyncpro" -gt 0 ];then
action "rsync $1 success!" /bin/true
else
action "rsync $1 fail!" /bin/false
fi
}
function main(){
if [ "$#" -ne 1 ];then
usage
elif [ "$1" = "start" ];then
st $1 #这里的$1 是指定函数的参数; 这种方式被称为将函数的传参转换成脚本文件命令行传参
elif [ "$1" = "stop" ];then
sp $1
elif [ "$1" = "restart" ];then
rt $1
else
usage
fi
}
main $1 # 函数的调用方式
执行结果: