2013-03-09

Checking battery life

I often work at the console, and I use the following bash script to check the battery life of my laptop.  It makes use of the ACPI (Advanced Configuration and Power Interface) in my Linux distro to retrieve information on the battery, and does some simple calculation to get the remaining time left to battery depletion.


#!/bin/bash
# check battery charge
rate=$(sed -n 4p /proc/acpi/battery/BAT1/state | sed 's/ \+/$/g' | cut -d$ -f3)
left=$(sed -n 5p /proc/acpi/battery/BAT1/state | sed 's/ \+/$/g' | cut -d$ -f3)
left=$(echo -e $left \* 60 / $rate | bc)
echo $left "mins left"

[Edited 2013-01-27]

I have modified the script to add a check if the laptop is plugged in and charging.  If so, exit gracefully with calculating the remaining time left.

#!/bin/bash
# skip if charging
state=$(cat /proc/acpi/battery/BAT1/state | sed -n 3p | awk '{print $3}')
if [ $state == 'charging' ]; then
    echo 'charging'
    exit 0
fi
# check battery charge
rate=$(sed -n 4p /proc/acpi/battery/BAT1/state | sed 's/ \+/$/g' | cut -d$ -f3)
left=$(sed -n 5p /proc/acpi/battery/BAT1/state | sed 's/ \+/$/g' | cut -d$ -f3)
mins=$(echo -e $left \* 60 / $rate | bc)
echo $mins "mins left"


[Edited 2013-04-10]
The Linux distro in this post is Backtrack 5 Release 3.