I have a systemd.service that run a script who can takes a long (like a couple of hours) or short time to finish, and when the script finishes it needs to call a cleanup script. My systemd.service file uses Type=oneshot.

The user can stop the service at any time, but then the cleanup script needs to be called.

I would like the service to be seen as active while the start script is running.

At the moment I have put the cleanup script in ExecStop and it seems to work. But sometimes I see that the service is failed, and I think that may be because of the long duration of the start script.

Can someone help me to understand how to achieve this with systemd please?

  • Regarding the service failure, there should be a message logged about the failure. sudo systemctl status should also show when it failed. If you want help understanding the service failure, you will need to ask a question including showing details about systemctl status, or at minimum the log messages, plus the .service file... I don't think the failure will be related to the long duration. (I mentioned earlier, Type=oneshot does not have a timeout by default. And the default timeout for other types is 90 seconds. So IMO, it would be easy to tell if the problem was a timeout.)
    – sourcejedi
    Jul 16, 2019 at 13:06
  • You want your cleanup script to run if the service fails, as well as when it is stopped normally, is that right? (As you commented in your previous question)
    – sourcejedi
    Jul 16, 2019 at 13:09

1 Answer 1


Note that the commands specified in ExecStop= are only executed when the service started successfully first. They are not invoked if the service was never started at all, or in case its start-up failed, for example because any of the commands specified in ExecStart=, ExecStartPre= or ExecStartPost= failed (and weren't prefixed with "-", see above) or timed out. Use ExecStopPost= to invoke commands when a service failed to start up correctly and is shut down again.


Additional commands that are executed after the service is stopped. [...] It is recommended to use this setting for clean-up operations that shall be executed even when the service failed to start up correctly.

I think you want to use ExecStopPost=.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.