🚀 Executive Summary
TL;DR: Default Linux battery notifications are often too passive, leading to unexpected laptop shutdowns during critical tasks. This guide provides solutions to create forceful, custom battery reminders at a 30% threshold using shell scripts.
🎯 Key Takeaways
- Default Linux battery notifications are easily missed by power users, necessitating a more urgent alerting mechanism for critical workflows.
- A shell script can monitor battery status and capacity by reading files in `/sys/class/power_supply/BAT*` and trigger a notification when discharging below a specified `THRESHOLD` (e.g., 30%).
- Solutions range from a quick `cron` job (which may require `DISPLAY` and `DBUS_SESSION_BUS_ADDRESS` exports for desktop notifications) to a more robust `systemd` timer setup for better integration and logging.
- For critical, out-of-desk alerts, the script can be extended to send push notifications to a phone using `curl` and a service like `ntfy.sh`, incorporating a `LOCK_FILE` to prevent notification spam.
Tired of your laptop dying during critical tasks? Learn how to create a simple, forceful battery reminder script for Linux using cron, systemd, or even push notifications to your phone.
That Time a Dead Laptop Almost Took Down Production
I remember it like it was yesterday. I was three hours deep into a production hotfix, SSH’d into prod-db-cluster-01, with a delicate `pg_basebackup` running. I was in the zone—terminal full screen, headphones on, laser-focused. The tiny, polite little battery icon in the corner of my screen had been whispering sweet nothings about being at 10% for a while, but I was ignoring it. “I’ll plug it in when this finishes,” I told myself. Famous last words. The screen went black. The backup aborted. The connection dropped. A cold sweat ran down my spine. All because the default power notification is designed for someone browsing Facebook, not for an engineer in the middle of open-heart surgery on a live system. Never again.
The “Why”: Default Notifications Are Too Polite for Their Own Good
Let’s be honest, the default battery notifications on most Linux distributions are passive-aggressive at best. They’re a small pop-up, easily missed, and they assume you’re not doing anything important. When you live in the terminal, you need something that gets in your face and demands attention. You need a system that understands the cost of an unexpected shutdown. The root of the problem isn’t a lack of information; it’s a lack of urgency and appropriate alerting for a power-user workflow.
So, let’s fix it. We’re engineers. We automate away our pain. Here are three ways to solve this, from a quick hack to a proper, robust solution.
Solution 1: The Quick and Dirty Cron Job
This is the classic, five-minute fix. It’s not elegant, but it gets the job done. We’ll write a tiny shell script and have the granddaddy of schedulers, `cron`, run it every few minutes.
Step 1: The Script
Create a file named ~/.local/bin/check_battery.sh and put this inside. Make sure to `chmod +x` it afterwards!
#!/bin/bash
# Find the correct battery, usually BAT0 or BAT1
BATTERY_PATH=$(find /sys/class/power_supply/ -name 'BAT*' | head -n 1)
if [ -z "$BATTERY_PATH" ]; then
# No battery found, exit silently
exit 0
fi
CAPACITY=$(cat "$BATTERY_PATH/capacity")
STATUS=$(cat "$BATTERY_PATH/status")
# The threshold to trigger the notification
THRESHOLD=30
if [[ "$STATUS" == "Discharging" && "$CAPACITY" -le "$THRESHOLD" ]]; then
# This requires libnotify-bin or a similar package to be installed
# We need to find the active user's display to send a desktop notification from cron
export DISPLAY=:0
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus"
notify-send --urgency=critical "LOW BATTERY WARNING" "Plug in your laptop! Current level: ${CAPACITY}%"
fi
Step 2: The Cron Job
Now, edit your user’s crontab by running crontab -e and add this line to run the script every 5 minutes:
*/5 * * * * /home/your_user/.local/bin/check_battery.sh
Heads Up: This is a bit of a hack. Getting desktop notifications to work from `cron` can be tricky because `cron` runs in a different environment. The `export DISPLAY` and `export DBUS_SESSION_BUS_ADDRESS` lines are common workarounds, but they aren’t guaranteed to work on every system setup (especially with Wayland).
Solution 2: The “Right Way” with Systemd Timers
For a modern Linux system, `cron` is a bit dated. Systemd timers are more robust, provide better logging (`journalctl`), and are designed to integrate properly with user sessions. This is how I’d do it for a permanent setup.
Step 1: The Service File
Create a file at ~/.config/systemd/user/battery-check.service. This file defines the “what” to run.
[Unit]
Description=Check laptop battery level and send notification
[Service]
Type=oneshot
ExecStart=%h/.local/bin/check_battery.sh
Notice we’re re-using the same script from Solution 1, but we can now remove the `export` lines from it, as systemd will handle the user environment correctly! Let’s update check_battery.sh to be simpler:
#!/bin/bash
BATTERY_PATH=$(find /sys/class/power_supply/ -name 'BAT*' | head -n 1)
if [ -z "$BATTERY_PATH" ]; then exit 0; fi
CAPACITY=$(cat "$BATTERY_PATH/capacity")
STATUS=$(cat "$BATTERY_PATH/status")
THRESHOLD=30
if [[ "$STATUS" == "Discharging" && "$CAPACITY" -le "$THRESHOLD" ]]; then
notify-send --urgency=critical "LOW BATTERY WARNING" "Plug in your laptop! Level: ${CAPACITY}%"
fi
Step 2: The Timer File
Now, create the schedule at ~/.config/systemd/user/battery-check.timer. This defines the “when” to run.
[Unit]
Description=Run battery-check service every 5 minutes
[Timer]
OnBootSec=1min
OnUnitActiveSec=5min
Unit=battery-check.service
[Install]
WantedBy=timers.target
Step 3: Enable and Start
Finally, tell systemd about your new timer and start it.
systemctl --user daemon-reload
systemctl --user enable --now battery-check.timer
You can check its status with systemctl --user status battery-check.timer.
Solution 3: The “I Can’t Afford to Miss This” Push Notification
Sometimes, even a critical desktop notification isn’t enough. What if you’ve walked away from your desk? This solution uses a free service like ntfy.sh to send a push notification straight to your phone. It’s gloriously over-engineered for a battery check, and I love it.
Step 1: Get Your Topic
Go to ntfy.sh and subscribe to a topic that’s hard to guess. For example, `my-secret-darian-laptop-battery`. Install the app on your phone and subscribe to that same topic.
Step 2: Modify The Script
Update your check_battery.sh script to send a `curl` request.
#!/bin/bash
# ... (same battery detection logic as before) ...
BATTERY_PATH=$(find /sys/class/power_supply/ -name 'BAT*' | head -n 1)
if [ -z "$BATTERY_PATH" ]; then exit 0; fi
CAPACITY=$(cat "$BATTERY_PATH/capacity")
STATUS=$(cat "$BATTERY_PATH/status")
THRESHOLD=30
# A simple lock file to prevent spamming notifications every 5 minutes
LOCK_FILE="/tmp/battery_notified.lock"
if [[ "$STATUS" == "Discharging" && "$CAPACITY" -le "$THRESHOLD" ]]; then
if [ ! -f "$LOCK_FILE" ]; then
curl -H "Title: URGENT: Laptop Battery Low" -H "Priority: urgent" -H "Tags: warning" -d "TechResolve laptop at ${CAPACITY}%. Plug it in NOW." ntfy.sh/my-secret-darian-laptop-battery
touch "$LOCK_FILE"
fi
elif [[ "$STATUS" == "Charging" ]]; then
# Remove the lock file once we start charging again
rm -f "$LOCK_FILE"
fi
You can then trigger this script using either the `cron` or `systemd` method from above. Now, when your battery gets low, your phone will buzz with an urgent alert. Problem solved.
Comparison of Solutions
| Method | Complexity | Reliability | Best For |
|---|---|---|---|
| Cron Job | Low | Medium | A quick fix when you just need something working now. |
| Systemd Timer | Medium | High | The “correct,” modern, and robust way for a permanent setup on your machine. |
| Push Notification | Medium | High | Critical situations where you absolutely cannot miss the alert, even if away from the keyboard. |
At the end of the day, choose the tool that fits your need. For me, the systemd timer is my daily driver. But you can bet if I’m on-call, I have that push notification service armed and ready. Don’t let a simple, solvable problem like a dead battery be your next outage post-mortem.
🤖 Frequently Asked Questions
âť“ How can I implement a forceful laptop battery reminder on Linux?
You can implement a forceful battery reminder on Linux by creating a shell script that reads battery capacity and status from `/sys/class/power_supply/` and then scheduling it with `cron`, `systemd` timers, or integrating `curl` with a push notification service like `ntfy.sh` for mobile alerts.
âť“ What are the advantages of custom battery monitoring over default Linux notifications?
Custom battery monitoring provides urgent, configurable alerts (e.g., critical desktop pop-ups, phone push notifications) that are not easily missed, unlike the passive default notifications. This is crucial for power users engaged in critical tasks where an unexpected shutdown could be costly.
âť“ What is a common pitfall when using cron for desktop battery notifications?
A common pitfall with `cron` is that it runs in a separate environment, making desktop notifications tricky. It often requires manual `export DISPLAY` and `export DBUS_SESSION_BUS_ADDRESS` lines in the script, which may not be universally reliable, especially with Wayland. `systemd` timers offer a more integrated solution.
Leave a Reply