I’ve been doing some work on my Debian Linux laptop lately and I have some nightly maintenance (disk check, btrfs tree balance) I want to do that will simply suck my battery dry if I’m not plugged into the wall. I did a quick web search to see how to check from a script to see if the system is on battery power or not and what I found was:
- Using outdated interfaces.
- fragile
- More complicated than it needed to be.
So I ended up writing something that took far less time than the original search did. How did I do it you ask?
Enter the acpi comm and. On old systems it uses proc and on new systems it uses sys. It cares so we don’t have to. It is not designed to be used in the way I want but writing a wrapper around it is easier than browsing either the proc or the sys interfaces on their own so I made this simple wrapper around it.
#!/bin/sh # Script to check if we are on battery power. # By Gerhard Mack <gmack@innerfire.net> # Licensed in the public domain. #scan for any on-line adaptors acpi -a | grep "on-line" > /dev/null 2>&1 #Grep will return 0 if it finds a matching line. if [ $? -eq 0 ]; then #we are on ac. Return false and exit exit 0 ; else #we are on battery. Return true and exit ; exit 1 ; fi
Example usage in bash:
onbattery
if [ $? -eq 1 ]; then # we are on battery so abort before sucking the battery dry exit fi