Battery Notifications in Linux

by Patrick Chong

Bash Script #

Put this anywhere and make the script file executable with with chmod +x.

#!/bin/bash

# watch --interval=5

CAPACITY=$(cat /sys/class/power_supply/BAT0/capacity)
STATUS=$(cat /sys/class/power_supply/BAT0/status)

if [[ (${CAPACITY} > 80) && (${STATUS} == "Charging")]]
then
/usr/bin/notify-send -u critical "Battery" "Disconnect Charger. Battery is above 80%"
elif [[ (${CAPACITY} < 20) && (${STATUS} == "Discharging")]]
then
/usr/bin/notify-send -u critical "Connect Charger. Battery" "Battery is below 20%"
fi

Crontab script #

Schedule to run script every 2 minutes

# for notify-send to work
DISPLAY=:0.0
XAUTHORITY=/home/$LOGNAME/.Xauthority
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus

*/2 * * * * <location of script>

Guide: https://crontab.guru/#*/2_*_*_*_*

Why keep laptop battery between 80-20 percent #

Have to admit that I had a hard time finding reputable sources, but I guess it could be true if many sources are saying the same thing?

Example Sources: