I have been a happy i3wm user for almost 4 years now.
A problem I faced early on was that I would often forget to connect my laptop’s charger so it would eventually shut down (thankfully I never lost any work thanks to Vim). 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #!/usr/bin/env bash THRESHOLD=10 # percent lock_path='/tmp/batmon.lock' lockfile -r 0 $lock_path 2>/dev/null || exit acpi_path=$(find /sys/class/power_supply/ -name 'BAT*' | head -1) charge_now=$(cat "$acpi_path/charge_now") charge_full=$(cat "$acpi_path/charge_full") charge_status=$(cat "$acpi_path/status") charge_percent=$(printf '%.0f' $(echo "$charge_now / $charge_full * 100" | bc -l)) message="Battery running critically low at $charge_percent%!" if [[ $charge_status == 'Discharging' ]] && [[ $charge_percent -le $THRESHOLD ]]; then DISPLAY=:0.0 /usr/bin/i3-nagbar -t warning -m "$message" fi rm -f $lock_path
Some things to note:
- Line 3: the threshold percentage is configurable
- Line 7: the script will exit if it’s already running to avoid multiple notifications e.g. when run by Cron
- Line 11: for greater accuracy, the percentage is calculated based on the last full charge of the battery instead of its nominal capacity (the difference between the two grows as the battery gets old)
- Line 17: a notification is shown using i3-nagbar (ships with i3wm)
I run the script once every minute with Cron:
* * * * * bash /home/agorf/work/dotfiles/scripts/batmon.sh
Email your comment