M BUZZ CRAZE NEWS
// news

How to run a command BEFORE shutdown on Ubuntu 21.04

By Jessica Wood

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:

  1. Open Terminal (if it's not already open)

  2. Ensure the script that you want to run at shutdown is executable:

    chmod +x ~/scripts/pre-shutdown.sh
  3. 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.

  4. Add the following lines to the .service file, 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.target
  5. Restart the daemon:

    sudo systemctl daemon-reload

That's all there is to it.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy