Transient services in systemd

System D is a very useful tool in Linux. We know it very well for managing services: turning them on and off, starting them, viewing the status.

Sometimes we would like to have the ability to run a service in a similar way, but without all the hassle with service files. It turns out that there is such a function, systemd offers transient services — run from the command line.

Example

First, let’s choose a simple command that we would like to run in the background. Let it be a script that writes lines to a file for a few seconds:

cat > test.sh < /tmp/test
for i in {1..10}; do
	echo "Repeated \$i times" >> /tmp/test
	sleep 1
done
echo "Done" >> /tmp/test
EOF
chmod +x test.sh

Let’s run it:

./test.sh

The program writes to a file in tmp, which also exists after script is finished:

cat /tmp/test

We should see:

Starting
Repeated 1 times
Repeated 2 times
Repeated 3 times
Repeated 4 times
Repeated 5 times
Repeated 6 times
Repeated 7 times
Repeated 8 times
Repeated 9 times
Repeated 10 times
Done

Let’s now use the systemd transient service to run our script:

sudo systemd-run -u systemd-transient-test ./test.sh

The command only took a moment. We can now check that the script is indeed running. Let’s use the cat command several times in a row to see the incoming lines in the file.

cat /tmp/test

Since we named the service when launching it, we can easily check its status by this name:

systemctl status systemd-transient-test

This will give us the familiar output for a service:

● systemd-transient-test.service - /home/ubuntu/./test.sh
     Loaded: loaded (/run/systemd/transient/systemd-transient-test.service; transient)
  Transient: yes
     Active: active (running) since Tue 2024-03-26 21:29:27 UTC; 4s ago
   Main PID: 1435 (test.sh)
      Tasks: 2 (limit: 4598)
     Memory: 584.0K
        CPU: 15ms
     CGroup: /system.slice/systemd-transient-test.service
             ├─1435 /bin/bash /home/ubuntu/test.sh
             └─1446 sleep 1

Transient services also work with journald :

journalctl -fu systemd-transient-test

There is a little more features of transient services. To read more about them, see the documentation.