Turns out it’s pretty easy to turn a Bash script into a system service that starts on boot and restarts automatically if it goes down. Here’s how.

You will need:

  • a Linux system that uses systemd
  • sudo privileges
  • a script you want to run as a service

Steps:

  1. Ensure the script is executable.

    chmod +x /home/hunter2/my-foo-project/qux-thing.sh
    
  2. Create a service file that contains information the host system will need in order to run the script. (If the service I’m setting up is part of a project, I like to store the service file with the rest of the project files.) Shortly we’ll use sudo ln -s to put a symbolic link to the service file in a place where systemd will find it.

    Here’s the contents of a suitable file named /home/hunter2/my-foo-project/qux-thing.service:

    [Unit]
    Description=My qux service (part of foo project)
    
    [Service]
    ExecStart=/home/hunter2/my-foo-project/qux-thing.sh
    Restart=always
    RestartSec=5s
    
    [Install]
    WantedBy=multi-user.target
    
    
  3. Now create a symbolic link to the service file so systemd will find it. Using a symbolic link has the additional benefit that you can modify the service file in the project folder and on the next daemon reload or system reboot, systemd will pick up the changes.

    sudo ln -s /home/hunter2/foo-project/qux-thing.service /etc/systemd/system/qux-thing.service
    
  4. Reload the systemd daemons (which now includes the new service) and put a few finishing touches on the new service’s configuration.

    sudo systemctl daemon-reload
    sudo systemctl enable qux-thing.service
    sudo systemctl start qux-thing.service
    
    
  5. At last, confirm that it’s up and running!

    sudo systemctl status qux-thing.service