1
  • Ubuntu 16.04
  • Bash version 4.4.0
  • nginx version: nginx/1.14.0

How can I test the Nginx configuration files in a Bash script? At the moment I use -t when I'm in a shell:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

But I would like to do this in a script?

  • 1
    Put the command into the script just like you would any other command. – DopeGhoti Jul 17 '18 at 15:50
  • 1
    what do you want the shell script to do? – Jeff Schaller Jul 17 '18 at 15:55
5

Use the exit status. From the nginx manpage:

Exit status is 0 on success, or 1 if the command fails.

and from http://www.tldp.org/LDP/abs/html/exit-status.html:

$? reads the exit status of the last command executed.

An example:

[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

A scripted example:

#!/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
|improve this answer|||||
  • In the script, you can do just if nginx -t 2>/dev/null; then ...; else ...; fi instead of testing on $?. – Kusalananda Jul 17 '18 at 16:13
  • @Kusalananda I know, I just thought my way would better explain what's going on – Dee Eff Jul 17 '18 at 16:14
  • @DeeEff I like the explanation and it makes sense. I was trying to compare the entire output of nginx -t. I learned a lot from this. Hats off to you mate. – Curious Sam Jul 17 '18 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.