I switch back and forth between Gnome and KDE and recently started to use Gnome again. As always I was appalled by the little amount of configuration allowed on a stock Gnome desktop. Running a script when switching between battery power and ac power is easy on KDE but on Gnome you have to configure this yourself. Some googling later I knew how to do it, but one thing struck me. Most posts run their script directly from the udev rule. This cannot be right for different reasons:
– You have no environment as udev runs in a minimal environment. So no access to $PATH, $HOME, etc.
– If the script runs for a long time it blocks udev and this can slow down things.
– You have no stout/stderr. Any output from your scripts will get lost.
Therefore it is preferred to kick of a service that will run your script:
First create an udev rule /etc/udev/rules.d/99-power-events.rules:
SUBSYSTEM=="power_supply",ACTION=="change",ENV{POWER_SUPPLY_ONLINE}=="1",RUN+="/bin/systemctl start on-ac.service"
SUBSYSTEM=="power_supply",ACTION=="change",ENV{POWER_SUPPLY_ONLINE}=="0",RUN+="/bin/systemctl start on-battery.service"
Then create two services /etc/systemd/system/on-ac.service
[Unit]
Description=Run script on AC power
[Service]
Type=oneshot
ExecStart=/home/USERNAME/.local/bin/power-hooks/on-ac.sh
User=USERNAME
Group=GROUPNAME
and /etc/systemd/system/on-battery.service
[Unit]
Description=Run script on battery power
[Service]
Type=oneshot
ExecStart=/home/USERNAME/.local/bin/power-hooks/on-battery.sh
User=USERNAME
Group=GROUPNAME
Replace USERNAME and GROUPNAME with the desired username and group.
Finally crate the scripts to run /home/$USER/.local/bin/power-hooks/on-ac.sh:
#!/bin/bash
echo "On ac power" > /home/$USER/Desktop/power-hooks.log
and /home/$USER/.local/bin/power-hooks/on-battery.sh
#!/bin/bash
echo "On battery power" > /home/$USER/Desktop/power-hooks.log
Note that sometimes it is easier to run the script as root user, especially if you want to use services as powerprofilesctl, brightnessctl or systemctl like I do. In that case change the user to root in the service definitions and remove the usergroup line. And it is probably better to put the on-battery.sh and on-ac.sh scripts in a system-wide location like /usr/local/bin.
For your convenience I put this all in a little git repo including an install and uninstall script: https://gitlab.com/raginggoblin/power-hooks. Adjust this to your liking, enjoy!