Forums

Restart shell script in background if not running anymore

Hey there,

I want a bash script (script.sh) to run 24/7 in the background which I'm trying to do with the following

nohup /home/<USER>/script.sh &

I'm struggling with building a second bash script which checks if the first one is currently running. If not, then it should restart it using the same line of code above. I would then schedule this second script to run every hour or so and restart script.sh if it's not running anymore.

I'm a complete noob when it comes to bash scripts.

Can someone lead me into the right direction or has a code example?

Thanks a lot!

Getting that working in a console would be tricky on PythonAnywhere, because different consoles can run on different machines, and communication between them isn't always instantaneous.

But there is a solution :-) If you use a scheduled task instead of a console command, and write it so that when it starts, if it sees another copy of itself already running, it exits immediately, then you should be able to get the effect you want. We have a help page explaining how to do that, with sample code.

Awesome. Just set this up and it seems to work. First test had two instances of the script running at first but after 20 seconds the second one threw an error and exited.

If this time delay can be expected then it's working.

Thanks a lot for the help!

That sounds about right for python to load, then do all the imports and then check that the other instance is running.