Created
November 17, 2025 15:51
-
-
Save mlow/031e1caf8fc0ee3b9e3b04b14d2b2424 to your computer and use it in GitHub Desktop.
battery-monitor.sh - A simple battery monitor script which sends desktop notifications when your battery level reaches predefined thresholds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # $HOME/.config/systemd/user/battery-monitor.service | |
| # Then: systemctl daemon-reload && systemctl enable --now --user battery-monitor.service | |
| [Unit] | |
| PartOf=graphical-session.target | |
| After=graphical-session.target | |
| Requisite=graphical-session.target | |
| [Service] | |
| ExecStart=%h/.local/bin/battery-monitor | |
| Restart=on-failure | |
| [Install] | |
| WantedBy=graphical-session.target |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # battery-monitor.sh - A simple battery monitor script which sends desktop | |
| # notifications when your battery level reaches pre-defined thresholds | |
| # Install to $HOME/.local/bin | |
| declare -A LAST_NOTIFIED | |
| CHECK_INTERVAL=33 | |
| THRESHOLDS=(5 10 15 20) | |
| notify() { | |
| notify-send "Battery Low" "Battery level is $2%" | |
| } | |
| while true; do | |
| BATTERIES=(/sys/class/power_supply/BAT*) | |
| for BATTERY_PATH in "${BATTERIES[@]}"; do | |
| BATTERY=$(basename "$BATTERY_PATH") | |
| charge_now=$(cat "$BATTERY_PATH/charge_now") | |
| charge_full=$(cat "$BATTERY_PATH/charge_full") | |
| percentage=$((charge_now * 100 / charge_full)) | |
| status=$(cat "$BATTERY_PATH/status") | |
| if [ "$status" = "Discharging" ]; then | |
| for threshold in "${THRESHOLDS[@]}"; do | |
| # Only notify once for a specific threshold until the battery begins charging | |
| if [ $percentage -le $threshold ]; then | |
| if [ "${LAST_NOTIFIED[$BATTERY]}" != "$threshold" ]; then | |
| LAST_NOTIFIED[$BATTERY]=$threshold # Track that this battery hit this threshold | |
| notify "$BATTERY" "$percentage" | |
| fi | |
| break | |
| fi | |
| done | |
| elif [ "$status" = "Charging" ] || [ "$status" = "Full" ]; then | |
| # Reset LAST_NOTIFIED when battery starts charging or is full | |
| unset LAST_NOTIFIED[$BATTERY] | |
| fi | |
| done | |
| sleep $CHECK_INTERVAL | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment