You can do this by creating a service file, then reloading systemd. Here's how:
Open Terminal (if it's not already open)
Ensure the script that you want to run at shutdown is executable:
chmod +x ~/scripts/pre-shutdown.sh
Create a file in /etc/systemd/system for the shutdown service. For the sake of this example, I'll call my file nighty-night.service.
Add the following lines to the .service file, modifying it as needed:
[Unit]
Description=Pre-Shutdown Processes
DefaultDependencies=no
Before=shutdown.target
# This works because it is installed in the target and will be
# executed before the target state is entered
# Also consider kexec.target
[Service]
Type=oneshot
ExecStart=/home/smeterlink/scripts/pre-shutdown.sh # your path and filename
[Install]
WantedBy=halt.target reboot.target shutdown.target
Reload systemd, enable the service so it starts at boot time, then start it up:
sudo systemctl daemon-reload
sudo systemctl enable nighty-night.service
sudo systemctl start nighty-night.service
You can see if it's running OK with systemctl status nighty-night
That's all there is to it.
root. Is that possible? – Smeterlink Apr 30 '21 at 01:33/etc/rc6.d/directory with a name likeK99-preshutdown.sh, then the script will run asrootbefore the shutdown. (Note: scripts in/etc/rc6.dare executed alphabetically so, to have your script run last, give it aK99prefix.) – matigo Apr 30 '21 at 01:38sudo systemctl enable nighty-night. – OscarGarcia Mar 31 '22 at 17:24