Run script as systemd under Ubuntu

Michael Schmidt
Published: Sep 3, 2024 by Michael Schmidt
Run script as systemd under Ubuntu

Create a shell script #

We create a simple example script

nano my_script.sh

Add the following content, this will print text to the console every 5 second:

#!/bin/bash
echo "Script started!"

while true; do
  # Wait for 5 seconds then print
  sleep 5
  echo "Script still running!"

done

Convert the script executeable:

chmod +x  ./my_script.sh

Create a Systemd Unit file #

Create a Unit file which allow to define a service in systemd

sudo nano /etc/systemd/system/my_script.service

Add the following contect:

[Unit]
Description=My Script Service
After=network.target

[Service]
ExecStart=/root/my_script.sh
Restart=on-failure
User=root
Group=root

[Install]
WantedBy=multi-user.target

Reload Systemd and Enable the Service #

Reload Systemd services:

sudo systemctl daemon-reload

Enable your new Systemd Unit file:

sudo systemctl enable my_script.service

Start service #

Start your service with the following command:

sudo systemctl start my_script.service

System Status and Logs #

Check status with the following command:
sudo systemctl status my_script.service

Response

my_script.service - My Script Service
     Loaded: loaded (/etc/systemd/system/my_script.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2024-09-03 22:30:43 CEST; 4s ago
   Main PID: 40436 (my_script.sh)
      Tasks: 2 (limit: 7059)
Read logs:
sudo journalctl -u my_script.service

Response

Sep 03 22:30:43 vmi2092881 systemd[1]: Started My Script Service.
Sep 03 22:30:43 vmi2092881 my_script.sh[40436]: Script started!
Sep 03 22:30:43 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:30:48 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:30:53 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:30:58 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:03 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:08 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:13 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:18 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:23 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:28 vmi2092881 my_script.sh[40436]: Script still running!
Sep 03 22:31:33 vmi2092881 my_script.sh[40436]: Script still running!