When you are prototyping and developing small scripts that you keep running, it might be annoying that they quit when an error occurs. If you want very basic robustness against these crashes, you can at least use a bash script to automatically restart your script on error.

The tool to use here is called until and makes this a breeze.

Let’s use a dumb example Python script called test.py:

import time

while True:
    print('Looping')
    time.sleep(5)
    raise Exception('Exception in loop')

It is in a loop and crashes every 5 seconds, so we can verify that our restart procedure works as expected.

When you execute python test.py, this is what you get:

/var/www/html$ python test.py 
Looping
Traceback (most recent call last):
  File "test.py", line 6, in <module>
      raise Exception('Exception in loop')
      Exception: Exception in loop

As expected the script dies after the Exception and then the process exits.

Now, let’s make it more robust using until in the file keep_running.sh:

#!/bin/bash

until python test.py
do
    echo "Restarting"
    sleep 2
done

Make the file executable by running chmod +x keep_running.sh and then we can execute it: ./keep_running.sh obtaining:

marc/var/www/html$ ./keep_running.sh 
Looping
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    raise Exception('Exception in loop')
Exception: Exception in loop
Restarting
Looping
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    raise Exception('Exception in loop')
Exception: Exception in loop
Restarting
Looping
^CTraceback (most recent call last):
  File "test.py", line 5, in <module>
    time.sleep(5)
KeyboardInterrupt
Restarting
^C

I added the sleep 2 in the script, so you can quickly use Ctrl + C twice to get out of the restart loop.

I hope you enjoyed this little bash tip - let me know what you think!