脚本安装编译安装nginx服务(适用于所有版本)

[root@50 ~]# cat nginx_install.sh 
#!/bin/bash

clear
echo "Preparations before installation..."
##variabled
NGINX_VERSION="nginx-1.16.0"
NGINX_INSTALL_DOC="/usr/local/nginx"
NGINX_USER="nginx"
NGINX_GROUP="nginx"
NGINX_CONFIGURE="--prefix=${NGINX_INSTALL_DOC} --user=${NGINX_USER} --group=${NGINX_GROUP} --with-http_ssl_module --with-http_stub_status_module"

##function
nginx_check(){
# 1、监测当前用户 要求为root 
if [  "$USER" != 'root' ];then
   echo "need to be root so that"
   exit 5
fi

# 2、检查wget命令
WGET_CHECK=$(rpm -q wget)
if [ $? -ne 0 ];then
yum -y install wget &> /dev/null
fi
}

nginx_install_pre(){
# 1、安装依赖
if ! (yum -y install gcc gcc-c++ pcre-devel zlib-devel elinks openssl* 1>/dev/null);then
	echo "ERROR:YUM install error"
	exit 5
fi
# 2、下载nginx源码包
if (wget http://nginx.org/download/${NGINX_VERSION}.tar.gz &>/dev/null);then
	tar zxf ${NGINX_VERSION}.tar.gz
	if [ ! -d ${NGINX_VERSION} ];then
		echo "ERROR:not found ${NGINX_VERSION}";exit 5 
	fi
else
	echo "ERROR:wget download file ${NGINX_VERSION}.tar.gz fail"
fi
}

nginx_install_make(){
(groupadd ${NGINX_GROUP} ;useradd -s /sbin/nologin -r -M -g ${NGINX_GROUP} ${NGINX_USER}) &>/dev/null
cd ${NGINX_VERSION}
echo "nginx configure..."
if ./configure ${NGINX_CONFIGURE} 1>/dev/null;then
	echo "nginx make ..."
    if make 1>/dev/null;then
		echo "nginx make install ..."
		if make install 1>/dev/null;then
			echo "nginx install success"
        else
			echo "ERROR: nginx install tail!";exit 5
		fi
	else
		echo "ERROR: nginx make tail!";exit 5
	fi
else
	echo"ERROR: nginx configure tail!";exit 5
fi
}

# 配置nginx开机自启,使用systemctl 管理nginx服务
nginx_enable(){
cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=${NGINX_INSTALL_DOC}/sbin/nginx
ExecReload=${NGINX_INSTALL_DOC}/sbin/nginx -s reload
ExecStop=${NGINX_INSTALL_DOC}/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl enable nginx.service 1>/dev/null
}

nginx_start(){
TEMP_NGINX=$(mktemp nginx.XXX)
if systemctl start nginx.service;then
    echo "nginx start SUCCESS!"
    clear
    elinks http://localhost -dump >${TEMP_NGINX}
    head -n +11 ${TEMP_NGINX}
    rm -f ${TEMP_NGINX}
    echo -e "\e[1;36m Manager Nginx:\e[0m \e[0;32m systemctl start|stop|status|restart| nginx.service \e[0m"
else
    echo "nginx stop FAIL"
fi

}

nginx_check
nginx_install_pre
nginx_install_make
nginx_enable
nginx_start

执行脚本

bash nginx_install.sh

脚本中定义了变量 需要安装其他nginx环境 只需要改变量就可以了!

  6 NGINX_VERSION="nginx-1.16.0"           #定义安装nginx版本
  7 NGINX_INSTALL_DOC="/usr/local/nginx"   #定义安装目录
  8 NGINX_USER="nginx"                     #定义nginx用户
  9 NGINX_GROUP="nginx"                    #定义nginx组
 10 NGINX_CONFIGURE="...省略"               #定义nginx编译需要模块及参数!
 # 注意:在定义 NGINX_CONFIGURE变量模块时  需要安装此模块需要的依赖(如:with-http_ssl_module模块就需要依赖openssl 否则就会报错!)

脚本执行成功后效果图:
脚本安装编译安装nginx服务(适用于所有版本)

上一篇:shell流程控制


下一篇:一个复制文件的Shell脚本