2

I've been laboring under the false assumption that mount points which are automatically created by systemd would also be automatically deleted, too. When I learned that systemd creates mount points for mount units if their mount points don't already exist, I figured that it behaved like macOS which creates and deletes mount points in /Volumes, respectively, before mounting and after unmounting a device.

One of my Linux setups is configured—either through a mount unit or fstab, depending on whicheber seems better at any given moment—to mount a tmpfs at /mnt. It's my equivalent of /Volumes. My mount units use /mnt/<mount point name> as their respective mount points. An example is mounting /dev/cdrom at /mnt/cdrom. (A side request: if someone could also tell me how to get non-root users' mounts that are performed with tools like udisksctl to mount in /mnt instead, that would be nice.)

I tried looking for a solution in the form of a directive I could add to each mount unit file that would call rmdir on its own mount point when the mount unit is "stopped", but there was nothing explicit in the search results I turned up. ExecStop was unrecognized in mount units by systemctl.

Hopefully, there's a graceful solution that is intended systemd developers for just this sort of situation.

1 Answer 1

2

I'm not aware of a built-in way to do this, but it can be done with a service template file:

# /etc/systemd/system/[email protected]
[Unit]
Description=Remove mount point when stopped
Before=%i.mount
PartOf=%i.mount

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=rmdir %f

Then you can just add this line to the [Unit] section of your mount unit:

Wants=cleanup-mount-point@%N.service

where %N, the name of the mount unit, becomes the %i in the above service template.

Or, if you're feeling adventurous, you can use a drop-in file to apply it to all mount units:

# /etc/systemd/system/mount.d/10-cleanup-mount-points.conf
[Unit]
Wants=cleanup-mount-point@%i.service
2
  • This is exactly what I wanted. For any systemd novices (like myself) out there, note that %i takes the instance name after the @. So, the second code block above only works if the mount unit itself is a template (with an @ in its name).
    – sssheridan
    Commented Jul 21, 2022 at 20:52
  • ...but unfortunately, mount units cannot be templated (man.archlinux.org/man/systemd.mount.5), so there's no @ or %i in mount units. The second code block should have %N (the full unit name) instead of %i (the part after the @, which is necessarily empty.)
    – sssheridan
    Commented Jul 21, 2022 at 22:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .