Sinisterly
[Bash] Show battery in prompt - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Computers (https://sinister.ly/Forum-Computers)
+--- Forum: Operating Systems (https://sinister.ly/Forum-Operating-Systems)
+--- Thread: [Bash] Show battery in prompt (/Thread-Bash-Show-battery-in-prompt)



[Bash] Show battery in prompt - Deque - 05-21-2013

This bash script that I wrote uses awk to get the number of bars to show how much the battery is loaded. It prints the bars in appropriate colors ranging from red to yellow to green to show the status. In addition it indicates if the battery is loading with the '~'.

Note that you maybe have to adjust the paths of BATTERY_DIR and ACAD_DIR to make it work. (This script is tested and works on Ubuntu 13.04)

Code:
#! /bin/bash

BATTERY_DIR=/sys/class/power_supply/BAT0
ACAD_DIR=/sys/class/power_supply/AC

BARS=$( awk '{print int( 5*($0/100) + 0.5) }' ${BATTERY_DIR}/capacity)

if [ $(cat ${ACAD_DIR}/online) -eq 1 ]; then
    echo -ne "~"
fi

if [ $BARS -gt 3 ]; then
    echo -ne "\[\033[1;32m\]" #green color
elif [ $BARS -gt 2 ]; then
    echo -ne "\[\033[1;33m\]" #yellow color
else
    echo -ne "\[\033[1;31m\]" #red color
fi

for (( c=1; c<=${BARS}; c++ ))
do
    echo -ne "|"
done

for (( c=${BARS} + 1; c<=5; c++ ))
do
    echo -ne " "
done

Old (Ubuntu 12.10)
Spoiler:
Code:
#! /bin/bash

BATTERY_DIR=/proc/acpi/battery/BAT1
ACAD_DIR=/proc/acpi/ac_adapter/ACAD

BARS=$( awk '/last full capacity/ {c = $4}
/remaining capacity/ {print int( (5*($3/c)) + 0.5 )}' ${BATTERY_DIR}/info ${BATTERY_DIR}/state)

if grep -q on-line ${ACAD_DIR}/state; then
    echo -ne "~"
fi

if [ $BARS -gt 3 ]; then
    echo -ne "\[\033[1;32m\]" #green color
elif [ $BARS -gt 2 ]; then
    echo -ne "\[\033[1;33m\]" #yellow color
else
    echo -ne "\[\033[1;31m\]" #red color
fi

for (( c=1; c<=${BARS}; c++ ))
do
    echo -ne "|"
done

for (( c=${BARS} + 1; c<=5; c++ ))
do
    echo -ne " "
done

Now you can use this i.e. to show the battery status in your prompt.

Example what to put in your .bashrc:

Code:
PS1="<\[\033[0;34m\]\u:\w\[\033[0;m\]>-(`battery.sh`\[\033[0;m\]):\$ "

Which will look like this (full battery):

[Image: 4xzz7iq5.png]

Or like this (low battery):

[Image: jlaqsxbz.png]


RE: [Bash] Show battery in prompt - MrGeek - 05-21-2013

Wow... nice tips sis
Thanks.
Copied to my clip board


RE: [Bash] Show battery in prompt - Deque - 06-23-2013

I upgraded to Ubuntu 13.04 and encountered that the script doesn't work anymore.
So I adjusted the bash script. See above. For users of the LTS the old script is still there in spoiler tags.