Displaying Custom Desktop Notifications on Linux

Recently, I've switched from a full blown desktop environment (Ubuntu's Unity) to using just a window manager, namely xmonad. (Although I'm still keeping the standard Ubuntu desktop installed as a fallback.) Now I don't have a tray with things like status indicators anymore. Of course, I could customize xmonad to have something equivalent, but I don't want that anymore. Not wasting screen estate with mostly redundant or completely unnecessary functionality is great. The bigger benefit though is that I am less distracted, as there are less unnecessary status indicators and notifications that would catch my attention.

However, there was one important thing that I've missed until now: battery status information. After my laptop has turned itself off during work for severaly times, without me noticing that the battery needed to be charged, I decided to write a small shell script that displays a notification whenever the remaining battery capacity is at a low level. The script invokes the notify-send utility, which is easy to use, comes with most Linux desktop systems, and presents notification bubbles that follow the freedesktop.org Desktop Notification Specification. The nice thing with the notifications is that they are both non-intrusive and hard to miss. They come and go, and don't occupy any fixed space.

Enough of the talk, here's the code:


# Monitors the remaining battery capacity on a Linux system, and
# sends a desktop notification if the remaining capacity falls below a
# certain threshold.


CAPACITY_REGEX="Battery 0: Discharging, (\d{1,3})%"

while true; do  
    remaining_capacity=$(acpi -b | perl -e "<> =~ /$CAPACITY_REGEX/ && print \${1}")

    if [ ! -z $remaining_capacity ] && [ $remaining_capacity -le $WARNING_THRESHOLD ]; then
        notify-send --urgency=critical "Battery Critically Low" "This computer has about ${remaining_capacity}% battery capacity remaining." --icon="$ICON"