User Tools

Site Tools


indexes:check_battery_state_with_bash_script

Battery state script

The idea with this script is to check whether a server running on a laptop has lost its power source and needs to shutdown nicely.

Prerequisite

I use the utility called “acpi” to easily draw out the required values. You could also get them directly from /proc but I'm lazy :-) Install acpi with this command:

sudo apt-get install acpi

The script

The script is very simple and I've put some comments into it to clarify what I'm doing.

#!/bin/bash

# Check if we're running on battery - the output will contain the word "Discharging" if we are 
# and generate one line thus putting the value "1" into the variable $state 
state=`acpi -b|grep Discharging| wc -l`

# Next we retract the percentage value of remaining power
procent=`acpi -b|awk -F ", " '{print $2}'|sed -e 's/\%//g'`

# If the power value is below 10% of battery capacity and we're running without power
# we shutdown the server
if [ $procent -lt 10 -a $state -eq 1 ]
then
        logger "Critical Low Power level - Shutting Down!"
        sleep 2
        halt
fi
indexes/check_battery_state_with_bash_script.txt · Last modified: d/m/Y H:i by domingo