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
...
CodePudding user response:
You can change systemd script to restart service always or on-failure https://www.freedesktop.org/software/systemd/man/systemd.service.html
CodePudding user response:
Being thoroughly unversed in bash,
(It is probably time to do a bash
scripting tutorial then. Note that this code will probably work with any POSIX compliant shell, not just bash
. So an sh
tutorial would do too.)
... there are two propositions that are opaque to me and require clarification:
> /dev/null 2>&1
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
.
and
[ $? != 0 ]
$?
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.
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 ...
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 for nginx 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.