1、编写业务逻辑代码
cat nginx_auto.sh
. /etc/init.d/functions
function Status () {
state=`systemctl status nginx|grep -w active | awk '{print $2}' | xargs`
if [ "$state" == "active" ];then
action "Nginx is Running Now." /bin/true
else
action "Nginx not running or has somes errors, Please try \"nginx -t\"" /bin/false
fi
}
function Start () {
systemctl start nginx
if [ $? -eq 0 ];then
action "Nginx is begining." /bin/true
else
action "Nginx can't be started. Please try \"nginx -t\"" /bin/false
fi
}
function Stop () {
systemctl stop nginx
action "Nginx has been stopped." /bin/true
}
function Reload () {
/usr/sbin/nginx -t
if [ $? -ne 0 ];then
action "Nginx has some error. Please try \"nginx -t\" to it." /bin/false
exit
fi
systemctl reload nginx
if [ $? -eq 0 ];then
action "Nginx is reloaded successfully." /bin/true
else
action "Nginx failed to reload. Please check if Nginx is on." /bin/false
fi
}
function Enable () {
grep -w '^/usr/sbin/nginx$' /etc/rc.local > /dev/null
if [ $? -ne 0 ];then
echo "/usr/sbin/nginx" >> /etc/rc.local
chmod +x /etc/rc.local
action "Nginx is enabled successfully." /bin/true
fi
}
function Disable () {
sed -i 's#^/usr/sbin/nginx$##' /etc/rc.local
action "Nginx is disabled successfully." /bin/true
}
function Exit() {
read -p "是否确认退出?[Y/N]" key
if ! [[ "$key" == "Y" || "$key" == "y" || "$key" == "N" || "$key" == "n" ]];then
echo "您的输入有误,请重新选择!"
fi
if [[ "$key" = "Y" || "$key" = "y" ]];then
echo "正在退出系统..."
exit 0 # 正常退出,状态码为0
elif [[ "$key" = "N" || "$key" = "n" ]];then
continue # 继续循环,回到上面的提示输入选项步骤
fi
}
2、编写主函数代码
cat nginx_main.sh
#!/bin/bash
# 导入nginx启停函数库
function main() {
. /root/test/nginx_auto.sh
echo "选择您要执行的操作"
select key in "state" "start" "stop" "restart" "reload" "enable" "disable" "Exit"
do
case $key in
state)
Status
;;
start)
Start
;;
stop)
Stop
;;
restart)
Stop
Start
;;
reload)
Reload
;;
enable)
Enable
;;
disable)
Disable
;;
Exit)
Exit
;;
*)
echo "Usage: $0 [start|stop|restart|reload|enable|disable|Exit]"
esac
done
}
main