应用场景: 经常发生某个进程宕机, 例如 Rsync 服务
实验环境: CentOS7
实验脚本:
- #!/bin/bash
- status=$(ps -aux | grep "rsync --daemon" | grep -v "grep" | wc -l)
- if [ $status -eq 0 ];
- then
- systemctl restart rsyncd.service
- else
- exit 0;
- fi
脚本分析:
步骤一: ps -aux | grep "rsync"
发现有多个 rsync 进程, 于是再次删选过滤, 找出需要的进程 "/usr/bin/rsync --daemon --no-detach"
步骤二: ps -aux | grep "rsync --daemon"
发现找到了需要的 rsync 进程, 但是多个一个 grep 筛选进程, 于是再次使用 grep -v 过滤
步骤三: ps -aux | grep "rsync --daemon" | grep -v "grep"
终于找到了需要的 rsync 进程, 接下来就需要结合 wc 计数命令来做判断条件, 再与流程控制语句 if 来编写脚本
步骤四: ps -aux | grep "rsync --daemon" | grep -v "grep" | wc -l
当 rsync 服务正在启动时, 得到的结果是 1, 当 rsync 服务停止时, 得到的结果是 0
来源: http://www.bubuko.com/infodetail-2496294.html