A server has nginx falling over frequently and needs to have a sude service nginx restart
executed.
A suggestion has been the following bash script:
service nginx status | grep 'active (running)' > /dev/null 2>&1
if [ $? != 0 ]
then
sudo service nginx restart > /dev/null
fi
Being thoroughly unversed in bash, there are two propositions that are opaque to me and require clarification:
> /dev/null 2>&1
and
[ $? != 0 ]
Because the response to service nginx status
returns a clear statement:
Active: failed (Result ...
and thus I would intuitively devise the if
statement to focus on failed
…
2
Answers
You can change systemd script to restart service always or on-failure
https://www.freedesktop.org/software/systemd/man/systemd.service.html
(It is probably time to do a
bash
scripting tutorial then. Note that this code will probably work with any POSIX compliant shell, not justbash
. So ansh
tutorial would do too.)That means "write stdout to /dev/null and write stderr (2) to the same place as stdout (1)". In short, throw away the output from
grep
.$?
expands to the exit code of the last command, so this means "test if the last command exited with a non-zero exit code; i.e. if it failed.In the case of a pipeline, the last command in the pipeline supplies the exit code. In this case, it will be the
grep
, which is specified to give a non-zero exit code if it doesn’t find any matching lines.Well, that doesn’t take account of the possibility that
service nginx status
doesn’t return any output for some reason. It is unlikely that will happen, but this version takes account of that. Also, the actual output of the systemd script fornginx status
is most likely not specified. It might change and that would break this script.Anyway … there are many ways to implement something like this. This way works, and that’s all that really matters.