I tried the following in a VBox with Ubuntu 22.04 running.
Create a systemd service in /etc/systemd/system/actionPreShutDown.service:
[Unit]
Description=Run before shutdown
#DefaultDependencies=no
After=local-fs.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/bin/bash /usr/local/bin/sync_before_shutdown.sh
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
Create the testfile /usr/local/bin/sync_before_shutdown.sh
Mine looked like this:
#!/bin/bash
timestamp=$(date '+%n---%a %b %e %H:%M:%S %Z %Y---%n')
SOURCE=`dirname -- "$0"`;
echo $SOURCE
echo "Shutting down now: '$timestamp'" >>$SOURCE/log.txt
so it basically wrote a log (into the still mounted filesystem) on "poweroff".
The "Poweroff" was triggered via the gnome menu and via command line.
Why /usr/local/bin
?
The code to be executed must belong to the system, not the user. Since I consider "backups" an admin task and the Linux Filesystem Hierarchy Standard writes:
The /usr/local hierarchy is for use by the system administrator when
installing software locally. It needs to be safe from being
overwritten when the system software is updated.
The bash will be in your path (i.e. you can call it from the console), but can only be executed as root.
But my final answer is, that it might not work stable. Poettering himself could not answer the question...
The main problem seems to be that there is no way to execute code before umount, since systemd runs parallel and shutdown and umount are triggered independently of each other. So I focused on available mounts and targets.
The line After=local-fs.target
enables the service after that target is bound, and therefore will end it before that target will be removed/stopped.
As an alternative you might setup your mount points from where you want to backup and proceed like this.
Since I spend a lot of time on this issue I'd appreciate an update if you found another solution.