Getting battery percentage in zsh

I’m on osx maverick still at home on my laptop and I spent part of today dicking around customizing my zsh shell. I wanted to be able to show my battery percentage in the shell and it’s really pretty easy.

First, the main shell function

function get_battery()
{
    current_battery=`system_profiler SPPowerDataType | grep -i "charge remaining" | awk '{print $4}'`

    max_battery=`system_profiler SPPowerDataType | grep -i "full charge capacity" | awk '{print $5}'`

    percent=`bc <<< "scale=4; ${current_battery}/${max_battery} * 100"`

    printf '%.0f' $percent 
}

This queries from the profiler the charge current and remaining, uses bc to get a floating point division, and then just shows the integer value of that (we could round it too but I was lazy).

Now, we just need to tie it into the prompt. I’m using the steef prompt by default and just tweaked it a bit:

battery_percentage="$(get_battery)%%"

directory_info="${_prompt_steeef_colors[5]}%~%f" 

datetime="%F{yellow}[%D{%a %I:%M:%S %p}]%f" # yellow [Day hh:mm:ss am/pm] followed by reset color %f

PROMPT="${battery_percentage} ${datetime} ${directory_info} ${vcs} 
""$ "

RPROMPT=""

The two percent symbols just escapes the percent symbol.

Make sure the battery_percentage function is defined before you load your prompt in your .zshrc file.

Now here’s what I got:

Screen Shot 2015-03-29 at 6.13.50 PM

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>