Tuesday, December 4, 2012

Yet Another Bash Battery Monitor

I wanted to tweak my bash battery monitor so that it displayed an updated value everytime a sub-shell returned. Coloring code adds cruft, so I removed it for this example. Here is what works for me:

(Add to .bashrc, PS1 section):
if [[ ( -e $HOME/.battery_check )   ]]; then
    PS1="[\$($HOME/.battery_check)] ${debian_chroot:+($debian_chroot)}\u@\h:\w\$ "
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi


(create an executable file $HOME/.battery_check with the following)
#!/bin/bash
BATTERY=/proc/acpi/battery/BAT0
REM_CAP=`grep "^remaining capacity" $BATTERY/state | awk '{ print $3 }'`
FULL_CAP=`grep "^last full capacity" $BATTERY/info | awk '{ print $4 }'`
BATSTATE=`grep "^charging state" $BATTERY/state | awk '{ print $3 }'`

CHARGE=`echo $(( $REM_CAP * 100 / $FULL_CAP ))`

case "${BATSTATE}" in
   'charged')
   BATSTT="$BLD="
   ;;
   'charging')
   BATSTT="$BLD⚡"
   ;;
   'discharging')
   BATSTT="$BLD-"
   ;;
esac

echo -e "${CHARGE}${BATSTT}"