Linux – Systemd : How to execute script at shutdown only (not at reboot)

arch linuxlinuxshutdownsystemd

There is a lot of solution here to execute a script at shutdown/reboot, but I want my script to only execute at shutdown.

I've tried to put my script in /usr/lib/systemd/systemd-shutdown, and check the $1 parameter, as seen here, but it doesn't work.

Any ideas ?

system : archlinux with gnome-shell

$systemctl --version                                                                                                                                                                                 
systemd 229
+PAM -AUDIT -SELINUX -IMA -APPARMOR +SMACK -SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN

Best Answer

I've finally found how to do that.

It's a bit hackish thought, but it works.

I've used some part of this thread : https://stackoverflow.com/questions/25166085/how-can-a-systemd-controlled-service-distinguish-between-shutdown-and-reboot

and this thread : How to run a script with systemd right before shutdown?

I've created this service /etc/systemd/system/shutdown_screen.service

[Unit]
Description=runs only upon shutdown
Conflicts=reboot.target
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/bin/bash /usr/local/bin/shutdown_screen
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Which will be executed at shudown/reboot/halt/whatever. (don't forget to enable it)

And in my script /usr/local/bin/shutdown_screen I put the following :

#!/bin/bash
# send a shutdown message only at shutdown (not at reboot)    
/usr/bin/systemctl list-jobs | egrep -q 'reboot.target.*start' || echo "shutdown" | nc 192.168.0.180 4243 -w 1

Which will send a shutdown message to my arduino, whom will shutdown my screen.

Related Question