如何测试 nginx 配置文件在 Bash 脚本中是否有效?

Cur*_*Sam 1 scripting configuration nginx

  • Ubuntu 16.04
  • Bash 版本 4.4.0
  • nginx 版本:nginx/1.14.0

如何在 Bash 脚本中测试 Nginx 配置文件?目前我在 shell 中使用 -t :

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Run Code Online (Sandbox Code Playgroud)

但我想在脚本中做到这一点?

小智 5

使用退出状态。从 nginx 联机帮助页:

成功时退出状态为 0,如果命令失败则退出状态为 1。

来自http://www.tldp.org/LDP/abs/html/exit-status.html

$? 读取最后执行的命令的退出状态。

一个例子:

[root@d ~]# /usr/local/nginx/sbin/nginx -t;echo $?
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is     successful
0
[root@d ~]# echo whatever > /usr/local/nginx/nonsense.conf
[root@d ~]# /usr/local/nginx/sbin/nginx -t -c nonsense.conf;echo $?
nginx: [emerg] unexpected end of file, expecting ";" or "}" in /usr/local/nginx/nonsense.conf:2
nginx: configuration file /usr/local/nginx/nonsense.conf test failed
1
Run Code Online (Sandbox Code Playgroud)

脚本示例:

#!/bin/bash
/usr/local/nginx/sbin/nginx -t 2>/dev/null > /dev/null
if [[ $? == 0 ]]; then
 echo "success"
 # do things on success
else
 echo "fail"
 # do whatever on fail
fi
Run Code Online (Sandbox Code Playgroud)