8

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 Answers1

14

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
    # 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

  5. 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.

TommyPeanuts
  • 1,157
matigo
  • 24,860
  • My mistake it has to be ran as root. Is that possible? – Smeterlink Apr 30 '21 at 01:33
  • Yes, if you add the script to your /etc/rc6.d/ directory with a name like K99-preshutdown.sh, then the script will run as root before the shutdown. (Note: scripts in /etc/rc6.d are executed alphabetically so, to have your script run last, give it a K99 prefix.) – matigo Apr 30 '21 at 01:38
  • It does not work just putting the script there. – Smeterlink Apr 30 '21 at 01:57
  • 2
    Step 5: enable the service: sudo systemctl enable nighty-night. – OscarGarcia Mar 31 '22 at 17:24
  • How to make the shutdown conditional? This solution executes the pre-shutdown.sh, but it shutdowns no matter what. Maybe a custom ctrl-alt-del.target? – Luis A. Florit Oct 29 '24 at 11:45