Running a script forever

Sometimes, you need to run a script « forever »: it needs to run even after reboot and needs to be restarted if it is killed.

There is many solutions for that, one of the best being the very well named forever. However, I wanted to do that in the most portable (a.k.a. which could run with minimal modification on any unix/linux system).

My solution is to generate a pid file and periodically check on it with cron. It is probably not the best solution but at least it uses only very widespread standard utilities and do not need any untrusted third-party scripts.

This is the boilerplate script (my_forever_script.sh), you just need to replace « #– YOUR ACTUAL SCRIPT » by your actual script 🙂 :

https://gist.github.com/elentarion/7320722

Then, you need to add your script to your crontab and run for example every five minutes. This will make sure that the maximum downtime for your script will be five minutes :

*/5 * * * * cd /home/MYUSER && ./my_forever_script.sh

If you want to test this script, you can start by replacing the line « #– YOUR ACTUAL SCRIPT » by something like:

echo "Hello World!"
sleep 42

This should be the output if you try starting the script multiple times (in the 42 seconds window):

# ./my_forever_script.sh &
No PID File.
Hello World!

# ./my_forever_script.sh &
Found PID 1337
my_forever_script.sh is already running.

If you are using it for critical tasks (monitoring, backup, logging, etc, …), be sure to test it thoroughly before deploying it into production.