How to show battery status in Zsh prompt

混江龙づ霸主 提交于 2019-11-29 14:41:14

问题


I think the answer is quite self explanatory.

I've been looking around for a software that already does this but I haven't had any luck. It's either not done in Zsh, or it's for another app, for example tmux. Point is I haven't been able to find it.

So my question is, is there already a pre-made script that somebody did that does this? If there is, could you please share a link to it.

If there isn't, what should I look into to making this script? I'm a newbie at Zsh scripting so bear that in mind.

The idea is that it outputs something along the lines of 67%. You get the point. ;)


回答1:


A very-very simple solution:

setopt promptsubst
PROMPT='$(acpi | grep -o "[0-9]*%)% '



回答2:


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)



回答3:


Even though this thread is quite old, I thought I post my version here, too:

I used the basic concept of steve losh's battery prompt but altered it in the first place to not use python but shell, which is far quicker and also changed the battery path to my arch linux distro. Additionally I added a green bold '+' at the end if my laptop is charging:

my battery function looks as follows:

function battery_charge {
  b_now=$(cat /sys/class/power_supply/BAT1/energy_now)
  b_full=$(cat /sys/class/power_supply/BAT1/energy_full)
  b_status=$(cat /sys/class/power_supply/BAT1/status)
  # I am displaying 10 chars -> charge is in {0..9}
  charge=$(expr $(expr $b_now \* 10) / $b_full)

  # choose the color according the charge or if we are charging then always green
  if [[ charge -gt 5 || "Charging" == $b_status ]]; then
    echo -n "%{$fg[green]%}"
  elif [[ charge -gt 2 ]]; then
    echo -n "%{$fg[yellow]%}"
  else
    echo -n "%{$fg[red]%}"
  fi

  # display charge * '▸' and (10 - charge) * '▹'
  i=0;
  while [[ i -lt $charge ]]
  do
    i=$(expr $i + 1)
    echo -n "▸"
  done
  while [[ i -lt 10 ]]
  do
    i=$(expr $i + 1)
    echo -n "▹"
  done

  # display a plus if we are charging
  if [[ "Charging" == $b_status ]]; then
    echo -n "%{$fg_bold[green]%} +"
  fi
  # and reset the color
  echo -n "%{$reset_color%} "
}



回答4:


Here is a version with color and written in ZSH.

In your .zshrc file

function battery {
    batprompt.sh
}
setopt promptsubst
PROMPT='$(battery) >'

and here is a batprompt.sh script for linux. You could adapt to other ways of reading the battery data or adapt the acpi version from the earlier post:

#!/bin/zsh
# BATDIR is the folder with your battery characteristics
BATDIR="/sys/class/power_supply/BAT0"
max=`cat $BATDIR/charge_full`
current=`cat $BATDIR/charge_now`
percent=$(( 100 * $current / $max ))

color_green="%{^[[32m%}"
color_yellow="%{^[[34m%}"
color_red="%{^[[31m%}"
color_reset="%{^[[00m%}"

if [ $percent -ge 80 ] ; then
    color=$color_green;
elif [ $percent -ge 40 ] ; then
    color=$color_yellow;
else
    color=$color_red;
fi
echo $color$percent$color_reset

Be warned that the ^[ you see in the color definitions is an Escape character. If a cut-and-paste does not work properly you will need to convert the ^[ to an Escape character. In VI/Vim you could delete the characters and then insert control-v followeed by the Escape key.




回答5:


This helpmed me for my mac,

pmset -g batt | grep -Eo "\d+%" | cut -d% -f1


来源:https://stackoverflow.com/questions/16125498/how-to-show-battery-status-in-zsh-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!