execute script before poweroff/reboot

1 – Create a script and enable the executable flag on it

cat > /usr/local/bin/poweroff_script.sh <<EOF
#!/bin/bash
touch /test     # create a test file
EOF

chmod +x /usr/local/bin/poweroff_script.sh

2 – Create unit file to run script with systemd at shutdown/reboot

cat > /etc/systemd/system/poweroff_script.service <<EOF
[Unit]
Description=Run my custom task at poweroff
DefaultDependencies=no
Before=poweroff.target halt.target shutdown.target
Requires=poweroff.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/poweroff_script.sh
RemainAfterExit=yes

[Install]
WantedBy=shutdown.target
EOF

3 – Refresh the systemd configuration files

systemctl daemon-reload

4 – Enable the script

systemctl enable poweroff_script.service

Leave a comment