How to run a command BEFORE shutdown on Ubuntu 21.04
I just want to run (as root) a command or script before each reboot/shutdown/poweroff on Ubuntu 21.04 (when I run the shutdown or poweroff commands, or using GNOME/KDE GUI options). I've tried putting the script inside /etc/init.d and making symlinks to /etc/rc6.d/ and /etc/rc0.d/ but doesn't work.
Wonder if there's such a line for sudo crontab -e.
1 Answer
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.shCreate a file in
/etc/systemd/systemfor the shutdown service. For the sake of this example, I'll call my filenighty-night.service.Add the following lines to the
.servicefile, modifying it as needed:[Unit] Description=Pre-Shutdown Processes DefaultDependencies=no Before=shutdown.target reboot.target halt.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 User=smeterlink Group= smeterlink ExecStart=/home/smeterlink/scripts/pre-shutdown.sh # your path and filename [Install] WantedBy=halt.target reboot.target shutdown.targetRestart the daemon:
sudo systemctl daemon-reload
That's all there is to it.
4