What is /usr/lib/systemd/system-shutdown ?

Leon Nunes - Apr 27 '22 - - Dev Community

Everyone probably has heard of startup scripts such as Cloud-init or user-data which is passed as a startup script even libvirt has this feature.

Running a shutdown script is however not mentioned much, now why would you need a shutdown script, sometimes, a shutdown script is needed to do various things such as collect diagnosis etc.

The path /usr/lib/systemd/system-shutdown/ runs these scripts, however they are run quite late hence the system is mostly in read-only mode, for example to create a log file one would have to do

cat /usr/lib/systemd/system-shutdown/debug.sh                                                                                                    
#!/bin/sh
mount -o remount,rw /
dmesg > /home/leon/shutdown-log
mount -o remount,ro /
Enter fullscreen mode Exit fullscreen mode

The other way is to use a systemd script:

cat /etc/systemd/system/demo.service
[Unit]
Description=Run my custom task at shutdown only
DefaultDependencies=no
Conflicts=reboot.target
Before=poweroff.target halt.target shutdown.target
Requires=poweroff.target

[Service]
Type=oneshot
ExecStart=/tmp/script.sh start
RemainAfterExit=yes

[Install]
WantedBy=shutdown.target
Enter fullscreen mode Exit fullscreen mode

This example is taken from here.

This is a pretty neat way to run shutdown scripts.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .