[systemd-devel] Help with running a script at shutdown and make it run first before other services

Dan Nicholson dbn at endlessos.org
Sun Dec 8 16:12:37 UTC 2024


On Fri, Dec 6, 2024 at 3:16 PM David Elie-Dit-Cosaque
<deliedit at redhat.com> wrote:
>
> Hi All,
>
> I am trying to create a systemd service that would execute a script at shutdown before any other services start receiving shutdown notifications. I came up with this:
>
> [Service]
> Type=oneshot
> RemainAfterExit=true
> ExecStart=/usr/bin/true
> ExecStop=/usr/local/bin/myscript.sh
> [Install]
> WantedBy=multi-user.target
>
> The script does run after shutdown is initiated but since it relies on other services which are also shutting down, it fails. Is there a way to order the shutdown so that  myscript.sh is completed first before continuing with the shutdown?

When stopping units, systemd reverses the ordering. For example, if
you have a service that has After=ssh.service, then the service is
started after ssh.service and stopped before it.

So, you just need to add After for any services or targets that you
care about even if you don't have ExecStart. Here's an example of a
service that runs on shutdown that does nothing when starting -
https://github.com/ostreedev/ostree/blob/main/src/boot/ostree-finalize-staged.service.

---
Dan


More information about the systemd-devel mailing list