Ubuntu – Script that starts with boot and auto-restart on failure


I'm trying to write an auto start script that starts on boot and restarts if it crashes. The start on boot is doable by simply adding the script to the


File, however my problem is the auto restart. I thought about exporting the $$ Variable into an external text file before starting the actual script, and using this with another script to check whether that pid still is running or not. My question is now how to check if a specific PID is still running and also if there is a more reliable way to do this.

Best Answer

What your script needs to perform in such a manner is systemd sevice.

An example would be the one below:

Description=My Script



This can be done in several ways:

  1. Place your script in another location and access it from your systemd service files.

  2. Place the code directly in the systemd service file.

I believe the first option is ideal in your situation. Now once done enable at boot with the normal systemctl commands, such as:

sudo systemctl enable myscript.service
sudo systemctl status myscript.service
sudo systemctl stop myscript.service
sudo systemctl start myscript.service