Skip to content

Instantly share code, notes, and snippets.

@fritz0705
Created January 10, 2011 14:58
Show Gist options
  • Select an option

  • Save fritz0705/772862 to your computer and use it in GitHub Desktop.

Select an option

Save fritz0705/772862 to your computer and use it in GitHub Desktop.
#!/bin/sh
# Usage: ./batt.sh COMMAND
#
# Use the environment variables `critical' and `sleep_time' to refine this
# script.
#
# Example: critical=50 ./batt.sh COMMAND
# Result: Every battery charge under 50% will result in COMMAND
if [ ! -d "/proc" ]
then
echo "There is no /proc directory. Is this Linux? Exit." >&2
exit 1
fi
if [ "`ls /proc/acpi/battery/`" = "" ]
then
echo "No batteries found. Exit." >&2
exit 1
fi
batteries=`echo /proc/acpi/battery/BAT* | sed 's/\s/\n/g' | awk '{print substr($argv, index($argv, "BAT"), length($argv))}' | sed 's/^BAT//'`
echo "Batteries: $batteries"
if [ "$sleep_time" = "" ]
then
sleep_time=60
fi
if [ "$critical" = "" ]
then
critical=10
fi
present_batteries=""
for battery in $batteries
do
if [ "`cat /proc/acpi/battery/BAT$battery/info | grep '^present:' | awk '{print $2}'`" = "yes" ]
then
if [ "$present_batteries" = "" ]
then
present_batteries="$battery"
else
present_batteries="$present_batteries $battery"
fi
fi
done
if [ "$present_batteries" = "" ]
then
echo "No present batteries found. Exit." >&2
exit 1
fi
echo "Present batteries: $present_batteries"
full_capacity=0
for battery in $present_batteries
do
full_capacity=`expr \`grep '^last full capacity:' /proc/acpi/battery/BAT$battery/info | awk '{print $4}'\` + $full_capacity`
done
if [ $full_capacity -eq 0 ]
then
echo "Hey. The sum of all full capacities is 0. There is a bug. Exit." >&2
exit 2
fi
echo "Full capacity: $full_capacity mWh"
while :
do
actual_charge=0
actual_status=discharging
for battery in $present_batteries
do
charging_state="`grep '^charging state:' /proc/acpi/battery/BAT$battery/state | awk '{print $3}'`"
if [ "$charging_state" = "charging" -a "$actual_status" = "charged" ]
then
actual_status=charging
elif [ "$actual_status" = "discharging" ]
then
actual_status=$charging_state
fi
actual_charge=`expr \`grep '^remaining capacity:' /proc/acpi/battery/BAT$battery/state | awk '{print $3}'\` + $actual_charge`
done
percent=`expr $actual_charge '*' 100 / $full_capacity`
if [ $percent -le $critical -a "$actual_status" = "discharging" ]
then
echo -n "[critical]"
cli=`echo $* | sed 's/__STATE__/'$actual_charge' mWh ('$percent' %)/g'`
$cli &
fi
echo "[$actual_status] $actual_charge mWh ($percent %)"
sleep $sleep_time
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment