How to show battery status in Zsh prompt
The other answer doesn't work on Mac OS X (no apci
).
I've taken bits of Steve Losh's zsh prompt in my prompt. It's not exactly what you're after - the arrows ▸▸▸▸▸▸▸▸▸▸
show the current battery state, and change color when the battery gets low. This method uses a Python script, which for completeness I'll add below. Here's a screenshot of my prompt in action:
Another method for OS X is presented on Reddit, using another short script:
ioreg -n AppleSmartBattery -r | awk '$1~/Capacity/{c[$1]=$3} END{OFMT="%.2f%%"; max=c["\"MaxCapacity\""]; print (max>0? 100*c["\"CurrentCapacity\""]/max: "?")}'
ioreg -n AppleSmartBattery -r | awk '$1~/ExternalConnected/{gsub("Yes", "+");gsub("No", "%"); print substr($0, length, 1)}'
Assuming this script is saved in ~/bin/battery.sh
:
function battery {
~/bin/battery.sh
}
setopt promptsubst
PROMPT='$(battery) $'
which looks like this:
To use Steve Losh's script, save the script somewhere, and use it in the battery()
function above.
The battery-charge Python script for OS X
#!/usr/bin/env python
# coding=UTF-8
import math, subprocess
p = subprocess.Popen(["ioreg", "-rc", "AppleSmartBattery"], stdout=subprocess.PIPE)
output = p.communicate()[0]
o_max = [l for l in output.splitlines() if 'MaxCapacity' in l][0]
o_cur = [l for l in output.splitlines() if 'CurrentCapacity' in l][0]
b_max = float(o_max.rpartition('=')[-1].strip())
b_cur = float(o_cur.rpartition('=')[-1].strip())
charge = b_cur / b_max
charge_threshold = int(math.ceil(10 * charge))
# Output
total_slots, slots = 10, []
filled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u'▸'
empty = (total_slots - len(filled)) * u'▹'
out = (filled + empty).encode('utf-8')
import sys
color_green = '%{[32m%}'
color_yellow = '%{[1;33m%}'
color_red = '%{[31m%}'
color_reset = '%{[00m%}'
color_out = (
color_green if len(filled) > 6
else color_yellow if len(filled) > 4
else color_red
)
out = color_out + out + color_reset
sys.stdout.write(out)
A very-very simple solution:
setopt promptsubst
PROMPT='$(acpi | grep -o "[0-9]*%)% '