The use of cron is possible, there are other (better) solutions (monit, supervisord etc.). But that is not the question; you asked for "the right way". The right way is difficult to define, but understanding the limits and problems in your code may help you.
Executing with normal cron
will happen at most once per minute. That means that you minecraft server may be down 59 seconds before it is restarted.
#!/bin/sh
You should have the #!
at the beginning of the line. Don't know if this is a cut/paste problem, but it is rather important. Also, you might want to use #!/bin/bash
instead of #!/bin/sh
to actually use bash.
ps auxw | grep start.sh | grep -v grep > /dev/null
Some may suggest to use ps -ef
but that is a question of taste. You may even use ps -ef | grep [s]tart.sh
to prevent using the second grep. The main problem however with this line is that that you are parsing the process-list for a fairly generic start.sh
. This may be OK if you have a dedicated server for this, but if there are more users on the server, you run the risk that someone else runs a start.sh
for something completely different.
if [ $? != 0 ]
then
There was already a comment about the use of $?
and clean code.
cd /home/minecraft/minecraft/ && ./start.sh && echo "Server restarted on: $(date)" >> /home/minecraft/minecraft/RestartLog.txt > /dev/null
It is a good idea to keep a log of the restarts. In this line, you make the execution of the ./start.sh
dependent on the fact that the cd
succeeds. Also, the echo only gets executed after the ./start.sh
exists.
So that leaves me with a question: does start.sh
keep on running as long as the server runs (in that case: the ps
-test is ok, but the && echo
makes no sense, or does start.sh
exit while leaving the minecraft-server in the background (in that case the ps
-grep
won't work correctly, but it makes sense to echo the log record only if start.sh
exits correctly).
fi
(no remarks for the fi
)