How to get a notify-send notification when your battery is running out 🪫

We'll be using a cronjob for this, but let's start by writing the shell script we'll be running:


CheckBattery.sh:
---------------------------------------------------------------------------------------------------------------------
#!/bin/sh
PERCENTAGE=$(cat /sys/class/power_supply/BAT0/capacity)
LOWLIM=10
PLUGGEDSTATE=$(cat /sys/class/power_supply/AC/online)
ISPLUGGED=1

if [ "$LOWLIM" -ge "$PERCENTAGE" ] && [ "$PLUGGEDSTATE" -ne "$ISPLUGGED" ] ; then
notify-send "🪫 Battery is at $PERCENTAGE %, consider charging"
fi
---------------------------------------------------------------------------------------------------------------------


It has two conditions; one: the battery charge is below 10 and two: the adapter isn't plugged in (as we wouldn't want to re-receive the message when we've already plugged in the adaptor). Before we can start using crontab we'll need to know our dbus session, we can know this by echoing DBUS_SESSION_BUS_ADDRESS. This is needed for notify send (due to X server stuff). Now we'll need to install a crontab program, I recommend cronie. Let's make a crontab entry via "crontab -e" and adding the following lines


*/10 * * * * env DBUS_SESSION_BUS_ADDRESS=YOURS LOCATIONOFSCRIPT

Where YOURS needs to be replaced with what you got after echoing that variable and LOCATIONOFSCRIPT speaks for itself. The first argument (*/10) tells cron to run this every 10 minutes.

And we're done!

Now if you want the opposite message, i.e when your battery is fully charged to pull the cord out. Then that's easy, just expand the script with the following:

if [ "$HIGHLIM" -le "$PERCENTAGE" ] && [ "$PLUGGEDSTATE" -eq "$ISPLUGGED" ] ; then
notify-send "🔋 Battery is fully charged"
fi

This might help preserve your battery longer.

back button home button