Angelos Orfanakos

Low battery notification in i3wm

I have been a happy i3wm user since 2012.

A problem I faced early on was that I would often forget to connect my laptop’s charger so it would eventually shut down. Even though i3status can display the current battery level, I have found that it is very easy to miss.

After many unexpected reboots, I decided to write a simple Bash script that displays a notification when the battery level percentage reaches or drops below a configured threshold:

#!/usr/bin/env bash

THRESHOLD=10
lock_path='/tmp/batmon.lock'

lockfile-create -r 0 -l $lock_path || exit
acpi_path=$(find /sys/class/power_supply/ -name 'BAT*' | head -1)
charge_status=$(cat "$acpi_path/status")
charge_percent=$(acpi | cut -d ' ' -f 4 | sed 's/[^0-9]//g')

if [[ $charge_status == 'Discharging' ]] && [[ $charge_percent -le $THRESHOLD ]]; then
  message="Battery running critically low at $charge_percent%!"
  DISPLAY=:0.0 /usr/bin/notify-send -u critical 'Low battery' "$message"fi

rm -f $lock_path

Some things to note:

  • The threshold percentage is configurable
  • The script will exit if it’s already running to avoid multiple notifications e.g. when run by Cron
  • A notification is shown using notify-send (ships with libnotify-bin on Debian)

I run the script every minute with Cron by placing the following under /etc/cron.d/batmon:

* * * * * agorf eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -ou agorf dbus-daemon)/environ)"; bash ~/work/scripts/batmon.sh