5
[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?

  • How would you distinguish: 1) a plain shutdown, 2) a restart, but the system is axed before its starts again, 3) a shutdown, and the system is manually restarted right after. In other words, why are you trying to make a distinction? To avoid some lengthy shutdown process during a restart? – xenoid Feb 4 '19 at 12:11
  • 1
    I want to wipe some files/logs when I shutdown my pc. I don't want to wipe files when I restart the pc. Thanks. – user993892 Feb 4 '19 at 12:56
1

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
| improve this answer | |
  • I think tha you do not understand my problem. My script is very simple, just delete some files. It is working but systemd.service start my script when I reboot and when I shutdown. As i said I want systemd service start my script to delete my files OLNY at SHUTDOWN. – user993892 Feb 6 '19 at 17:03
  • 1
    Mike, the example provided does exactly what you described. You just have to write your rm instead of my printf. Everytime you are in every shutting process (halt, power-off and reboot) your test.sh will be executed; inside your test.sh you have to check, as provided example, if you are not rebooting in order to execute the actual piece of code you want ONLY when you SHUTDOWN – ingroxd Feb 6 '19 at 18:47
  • It is working but I have a problem. I use the srm command, it takes a long to wipe the files so my script It doesn't finsh and system shutdown. How can I start shutdown systemd service after my script end? – user993892 Feb 6 '19 at 21:46
  • Pretty much another problem... You can try with something like this: g-loaded.eu/2008/11/28/delayed-shutdown-initscript – ingroxd Feb 7 '19 at 12:46
  • I solved the problem with this command TimeoutSec=300min. Thank you – user993892 Feb 7 '19 at 12:54

Your Answer

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