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
PERCENTAGE="$(...)"
: This line callspmset -g batt
, which provides detailed battery information. It then usesgrep
andcut
to extract only the numerical percentage.CHARGING="$(...)"
: This checks the output ofpmset -g batt
for the string 'AC Power'. If found, the$CHARGING
variable will not be empty, indicating the device is charging.if [ "$PERCENTAGE" = "" ]; then ...
: If no percentage is found (e.g., on a desktop Mac), the script exits.case "${PERCENTAGE}" in ...
: Acase
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.if [[ "$CHARGING" != "" ]]; then ...
: If the$CHARGING
variable is not empty, it overrides the icon with a charging symbol (e.g., a lightning bolt).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 itsicon
to the chosen symbol and itslabel
to the current percentage.