# nginx 相关脚本

  • 入托执行脚本的时候脚本带有 nginx 字样,需要忽略掉,使用 grep -v $this_pid

  • ps -ef | grep -v $this_pid | grep nginx | grep -v grep 的返回值可能是输出的字符串,&>/dev/null将其丢弃到垃圾箱,因为我们只需要其$?的状态

# 查看 nginx 是否在运行

#!/bin/bash
#

this_pid=$$

function is_nginx_running() {

    ps -ef | grep nginx | grep -v $this_pid | grep -v grep >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

is_nginx_running && echo "Nginx is running" || echo "Nginx is stopped"

# 监听 nginx,如果断开则重启(基础版本)

  • sleep 表示休眠,检测间隔

  • nohup 的使用,查看后台输出 tail -f nohup.out

sh nginx.sh

# nohup sh nginx.sh &  将输出放在后台

this_pid=$$ # 获取到该执行脚本的pid

function nginx_daemon() {
    status=$(ps -ef | grep -v $this_pid | grep nginx | grep -v grep &>/dev/null)
    if [ $? -eq 1 ]; then
        systemctl start nginx && echo "Start Nginx Successful" || echo "Failed To Start Nginx"
    else
        echo "Nginx is RUNNING Well"
        sleep 5
    fi
}

while true; do
    nginx_daemon
done