编写脚本httpd监控脚本:要求可以输入start | stop | restart | status 并实现相对应的功能
分析:仅查看apache的状态时有输出信息,此时需要截出有关描述apache状态的信息;其他的若执行成功则均无输出结果
##本机已经安装过了apache
[root@localhost mnt]# rpm -q httpd
httpd-2.4.6-40.el7.x86_64
##过滤出含有Active关键字的行信息
[root@localhost mnt]# systemctl status httpd | grep "Active"
Active: active (running) since Fri 2018-12-28 08:32:20 CST; 1min 34s ago
## $3输出第3个字符(默认以空格为分隔符)
[root@localhost mnt]# systemctl status httpd | grep "Active" | awk '{print $3}'
(running)
## -F表示指定分隔符
[root@localhost mnt]# systemctl status httpd | grep "Active" | awk '{print $3}'| awk -F\( '{ print $2}' | awk -F\) '{ print $1}'
running
编写脚本:
[root@localhost mnt]# vim apache_service.sh
####################
#!/bin/bash
echo -e "\033[35m start 开启apache\033[0m"
echo -e "\033[36m stop 关闭apache\033[0m"
echo -e "\033[33m restart 重启apache\033[0m"
echo -e "\033[32m status 查看apache\033[0m"
echo -e "\033[34m Q/q 退出系统\033[0m"
while true
do
read -p "Please input an option: " i
case $i in
start)
echo -e " \033[35m ` systemctl start httpd && echo "apache has already started" || echo "apache start filed!" ` \033[0m "
;;
stop)
echo -e " \033[36m ` systemctl stop httpd && echo "apache has already stoped" || echo "apache stop filed!" ` \033[0m "
;;
restart)
echo -e " \033[33m ` systemctl restart httpd > /dev/null && echo "apache has already restarted" || echo "apache restart filed!" ` \033[0m "
;;
status)
echo -e " \033[32m ` systemctl status httpd | grep "Active" | awk '{print $3}'| awk -F\( '{ print $2}' | awk -F\) '{ print $1}' ` \033[0m "
;;
Q|q)
echo -e "\033[34m say good bye \033[0m "
exit 1
;;
*)
echo -e "\033[31m ERORR: Please input a correct option \033[0m "
esac
done
注释:
\033[35m \033[0m ##35表示颜色 0m表示关闭属性;注意:必须加-e解析才能识别颜色
while true ##表示这是一个无限循环;即为死循环
case ##case语句用于多个条件
执行脚本:
[root@localhost mnt]# sh apache_service.sh