Configure a systemd Service to Perform Side Effects and Corresponding Cleanup

Published by Philipp Schuster on

Problem and Motivation

For a Linux-based demo setup, I need certain side effects and corresponding cleanup steps every time the system boots or relevant system configuration changes. I’m using NixOS, and systemd is the easiest and most powerful way to manage setup tasks at system startup or on substantial system configuration changes in NixOS. I didn’t need a daemon running in the background (which is the major purpose for systemd services), but specifically certain side effects and corresponding cleanup. Lightweight shell script to perform the relevant actions are more than sufficient – invoked by systemd.

⚠️ Please note that using systemd is one possible way of achieving this. There might be others, depending on your system / Linux distribution.


From my understanding, research, and reading the man pages, using a Type=oneshot service with RemainAfterExit=true is the right configuration to achieve that. The following (with manually removed clutter) configuration file my-service.service shows a valid complete example:


ExecReload=/path/to/your/setup-script --reload
ExecStart=/path/to/your/setup-script --start
ExecStop=/path/to/your/setup-script --stop


We need Type=oneshot so that systemd blockingly waits for the command behind ExecStart to exit. We need RemainAfterExit=true so that ExecStop is not immediately executed after ExecStart finishes, but when the service is (naturally or manually) stopped, as if it was a daemon.

Note that After=<service> and WantedBy=<target> highly depend on your use-case. This is what worked in my case.

Philipp Schuster

Hi, I'm Philipp and interested in Computer Science. I especially like low level development, making ugly things nice, and de-mystify "low level magic".


Leave a Reply

Your email address will not be published. Required fields are marked *