Shell脚本打卡30day---day5

题目:开发启动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   # 函数的调用方式

执行结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值