Linux – Run a script on systemd service ONLY at shutdown not restart

linuxshutdownsystemd

[Unit]  
Description=test  
Before=shutdown.target

[Service]  
ExecStart=/bin/true  
ExecStop=/usr/local/bin/test.sh  
RemainAfterExit=yes

[Install]  
WantedBy=multi-user.target

I tried a lots of examples, but didn't work. The above example works both restart and shutdown. I want to work ONLY at shutdown.

I don't have server. It is my personal pc. I have Gnu/linux os. Is it possible to run script only at shutdown and not restart?

Best Answer

You can test in your script if you are rebooting, halting or powering off the system and decide what to do accordingly.

For example:

#!/bin/bash
if ! systemctl list-jobs | grep -q -e "reboot.target.*start"; then
   printf "Not rebooting\n"
fi

In man systemd.special you can see all targets. You may want to pay more attention to:

  • shutdown.target
  • reboot.target
  • halt.target
  • poweroff.target
Related Question