Skip to content

POSIX-Complaint Battery-Management-Script

I use dwm as my window-manager and often forget to look at my bar to read the battery-percentage, so i wrote this. The script is designed as a Finite-State-Machine and depends on dunst and acpi. Feel free to reuse, change and critique.

#!/usr/bin/sh

STATE=0
STATE_PREV=0

while true; do

    charge=$(acpi)
    percentage=$(echo $$charge | awk '{print $4}' | sed -E 's/%,?//g' | sort -r | head -n 1)

    STATE=0  # Cordless use; default

    if $percentage -le 10; then
	STATE=1  # Critical capacity
    elif test "${charge#*Charging}"; then
	STATE=2  # Charging
    elif test "${charge#*Full}"; then
	STATE=3  # Fully Charged
    fi

    if $STATE -eq 1 && $STATE_PREV -ne 1; then
	dunstify --urgency=critical -t 0 'Battery' 'Battery less than 10%'
    elif $STATE -eq 2 && $STATE_PREV -ne 2; then
	dunstify -t 5 'Battery' 'Battery is charging'
    elif $STATE -eq 3 && $STATE_PREV -ne 3; then
	dunstify -t 5 'Battery' 'Battery fully charged!'
    fi
    
    sleep 40
    STATE_PREV=$STATE
    
done

Edited 8 Oct 2019. We only hold this version.

2 points6 comments
Open on Reddit
About this post
Posted
Archived
Edited
Score
2 · 100% up
Kind
Text
ID
depssa

Author

44
posts
81
comments
2
media
View profile

6 comments

It doesn't seem to handle the case of multiple batteries..! And sh does not understand [[... See https://shellcheck.net

5 points

Thanks for pointing me to shellcheck! I haven't heard of it before. Will use and improve the above tomorrow.

3 points

I updated the script. Should be POSIX-complaint now.

1 points

You're right about the multiple batteries. However i'm running the script with sh and it works.

0 points

Your sh is most likely bash anyway. Try and install busybox and use its shell to execute the script.

As already said, I recommend you get shellcheck installed on your machine. I can see that there are several quotes missing at first sight.

2 points

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.