Linux – How to change Power button shutdown action to run a script under systemd

linuxshutdownsystemd

How does one change the power button shutdown action under say debian 10 systemd to run a custom script instead of shutting down the system?

Back when this was handled by acpi one could edit the scripts in /etc/acpi. The only suggestion I have found thus far is to replace various power related binaries with my script.

Is there a way to do this without replacing binaries?

Best Answer

It depends on what you want to do.

  • If you just need to temporarily block poweroff while you're running some operation, see systemd-inhibit. You can also block sleep, suspend, etc. like this. You can also temporarily (as long as your program is running) tell systemd to ignore the power button, intended to let some other program act on it instead.

  • If you just want to run some extra code before shutdown, then you can have your service started by poweroff.target. You may also want to consider shutdown.target and reboot.target. (I think you could also change the poweroff.target to not pull in systemd-poweroff.service if you want to change entirely what the power button does — but beware things like systemctl poweroff and poweroff go through that too).

  • If you want to disable systemd's handling of the power button entirely, you'll first have to know it's actually logind that normally does it. The HandlePowerKey option in /etc/systemd/logind.conf lets you disable it (by setting to ignore). You could then have some other program listen for the keys.

Related Question