Scripting
如何測試 nginx 配置文件在 Bash 腳本中是否有效?
- Ubuntu 16.04
- 重擊版本 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
但我想在腳本中做到這一點?
使用退出狀態。從 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
一個腳本範例:
#!/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