Linux – Run script when power button pressed

bashkey-bindinglinuxpower-managementUbuntu

When I push the power button, I want to run a script. For the sake of this scenario, say file.sh. So when I push the power button, I want to run file.sh and only file.sh.

Most of the solutions I found involved editing /etc/acpi/powerbtn.sh, but that file does not exist on my system. (I'm running Ubuntu 19.04) I tried creating it and populating it with the standard contents, but it didn't work. I also tried listening for key presses with acpi_listen, but nothing happened when I pushed keys, so I don't know if I just did it wrong or what. I tried using xev,which did pick up key events but nothing registered when I hit the power button.

Anyone know how to accomplish this, or what I am doing wrong?

P.S. I should mention, I would prefer a solution that can be done on the command line, ideally one without any 3rd party software. Thanks.


Similar question, but with no solutions:

https://askubuntu.com/questions/473693/run-a-script-when-power-button-is-pushed

Basically looking for the Linux equivalent of what they did here:

https://stackoverflow.com/questions/12434863/executing-a-batch-script-on-windows-shutdown


EDIT: this is what I get from syslog:

Feb 9 13:01:01 joe-Aspire-E5-576G gnome-session-binary[1624]: Entering running state

And this is my file in events:

event=button/power action=/home/ragnvaldr/Desktop/test/sc.sh
`

Best Answer

Your question is answered in the EXAMPLE section of man acpid. I will adapt to your needs.

  • As a root create a file named /etc/acpi/events/power with contents like this:
event=button/power
action=/usr/bin/logger "ACPI_POWER_BTTN_TEST: %e"
  • Then run service acpid restart.

  • Tail the syslog file like this /usr/bin/tail -f /var/log/syslog

  • Press the power button to see your test message in syslog.

  • Change the action= line in the power file appropriately to point to your custom script.

Related Question