Plugin: battery.sh

This plugin fetches the current battery percentage and charging status from macOS using the pmset command-line utility.

Usage

This script is typically used with an item that updates periodically and also subscribes to power-related system events.

sketchybar --add item battery right \
           --set battery \
                 update_freq=120 \
                 script="$PLUGIN_DIR/battery.sh" \
           --subscribe battery system_woke power_source_change
  • update_freq=120: The script runs every 120 seconds to catch gradual changes in battery level.
  • --subscribe battery system_woke power_source_change: The script also runs immediately when the system wakes from sleep or when the power adapter is plugged in or unplugged.

Source Code

#!/bin/sh

PERCENTAGE="$(pmset -g batt | grep -Eo "\d+%" | cut -d% -f1)"
CHARGING="$(pmset -g batt | grep 'AC Power')"

if [ "$PERCENTAGE" = "" ]; then
  exit 0
fi

case "${PERCENTAGE}" in
  9[0-9]|100) ICON=""
  ;;
  [6-8][0-9]) ICON=""
  ;;
  [3-5][0-9]) ICON=""
  ;;
  [1-2][0-9]) ICON=""
  ;;
  *) ICON=""
esac

if [[ "$CHARGING" != "" ]]; then
  ICON=""
fi

# The item invoking this script (name $NAME) will get its icon and label
# updated with the current battery status
sketchybar --set "$NAME" icon="$ICON" label="${PERCENTAGE}%"

Explanation

  1. PERCENTAGE="$(...)": This line calls pmset -g batt, which provides detailed battery information. It then uses grep and cut to extract only the numerical percentage.
  2. CHARGING="$(...)": This checks the output of pmset -g batt for the string 'AC Power'. If found, the $CHARGING variable will not be empty, indicating the device is charging.
  3. if [ "$PERCENTAGE" = "" ]; then ...: If no percentage is found (e.g., on a desktop Mac), the script exits.
  4. case "${PERCENTAGE}" in ...: A case statement is used to select a different battery icon (from a Nerd Font) based on the current percentage, creating a visual indicator that drains as the battery depletes.
  5. if [[ "$CHARGING" != "" ]]; then ...: If the $CHARGING variable is not empty, it overrides the icon with a charging symbol (e.g., a lightning bolt).
  6. sketchybar --set "$NAME" ...: This is the final and most important step. It tells SketchyBar to update the item that ran this script ($NAME) by setting its icon to the chosen symbol and its label to the current percentage.