I have a systemd service file of the following kind.

Description=Mount some special file systems



The script /root/some-complicated-mounts.sh mounts some file systems.

The service was not working until I added the RemainAfterExit=yes statement. Without this statement the mounts that are done by the script seem to disappear, eventhough according to the logs the script is executed successfully.

I would like to know, why I need the RemainAfterExit=yes statement and where this behavior is described in the systemd documentation.


This oneshot service will not work without RemainAfterExit=yes because systemd will consider that the unit will go inactive as soon as the some-complicated-mounts.sh script is finished and, at that point, it will stop the unit, which includes executing the ExecStop= command, which will then proceed to unmount the filesystems by executing the some-complicated-umounts.sh script.

Using RemainAfterExit=yes solves this issue, since the unit is then considered started after the ExecStart= command completes and is kept in an active state. So the ExecStop= command will only execute if the unit is stopped explicitly (with a systemctl stop command) or as part of a normal shutdown procedure, when all units are stopped.

Regarding documentation, the systemd documentation actually has an example for this exact scenario: see "Example 3. Stoppable oneshot service" on the man page for systemd.service(5). The description for the use case of the example says:

Similarly to the oneshot services, there are sometimes units that need to execute a program to set up something and then execute another to shut it down, but no process remains active while they are considered "started". [...]

For this, systemd knows the setting RemainAfterExit=yes, which causes systemd to consider the unit to be active if the start action exited successfully.

Also contrast that with Example 2, which is a oneshot service without an ExecStop=.

(Unfortunately the documentation for RemainAfterExit= itself is too terse and doesn't really go these details. There's probably an opportunity for improvement to the documentation of that option here.)

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.