Run shell script before shutdown – linux

before_shutdown.sh

#!/bin/bash
#remove file older than 7 days
find /var/log -name "*.log" -type f -mtime +7

#test
touch "/opt/before_shutdown_tmp_file_$(date +%s)"
  • Create systemd service
echo '[Unit]
Description=before_shutdown

[Service]
ExecStart=/bin/true
Type=oneshot
RemainAfterExit=true
ExecStop=/opt/before_shutdown.sh

[Install]
WantedBy=multi-user.target' > /etc/systemd/system/before_shutdown.service
systemctl daemon-reload

systemctl enable before_shutdown

systemctl start before_shutdown

https://unix.stackexchange.com/questions/39226/how-to-run-a-script-with-systemd-right-before-shutdown