Keeping a process running with a 3 line Bash script

While you are running a long running process, you may want to run it again if it stops or is watching some process that should be running all the time. At first look at this might seem best to…

  • Create some cron running a script that checks output of “ps aux | grep myprogram”, run it if it is not running.
  • Wrap some other Python script calling it and at the end wait and try running again.
  • Check in on the process and see what might be wrong. (Not great, if it is a process you want to be checking errors in you should be using Sentry anyway)

However there is a simpler option: create some run.sh:

mycommand
sleep 10
sh ./run.sh

Now running the command (“sh ./run.sh”) will run the command and rerun if it crashes! Check it out and kill the process, you will see “Terminated”…wait 10s, and it will start again.

As always if manually running this through ssh you should use the screen command.

Leave a Reply

Your email address will not be published. Required fields are marked *

seventy five − 69 =