Last active
August 17, 2023 04:16
-
-
Save resilar/1403efb80d3c7824807714549ce2e80c to your computer and use it in GitHub Desktop.
Linux shell script implementation of `acpi -b`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Show battery information similar to `acpi -b` | |
if [ -n "${*:-$BAT}" ]; then for BAT in "${@:-$BAT}"; do echo "$BAT"; done | |
else find /sys/class/power_supply/ -maxdepth 1 -name 'BAT*' | LC_ALL=C sort | |
fi | while IFS= read -r BAT; do | |
if [ ! -r "$BAT" ] || [ ! -r "$BAT/uevent" ]; then | |
printf '%s unreadable\n' "$BAT" >&2 | |
continue | |
fi | |
sed 's/^POWER_SUPPLY_\([^=]*\)=\(.*\)$/\1="\2"/' "$BAT/uevent" >/tmp/$$.bat | |
. /tmp/$$.bat | |
rm -f /tmp/$$.bat | |
for SUFFIX in STATUS POWER_NOW ENERGY_NOW ENERGY_FULL; do | |
if [ -z "$(eval printf '%s' '$'$SUFFIX)" ]; then | |
if [ "$SUFFIX" = "ENERGY_FULL" ]; then # Dead battery | |
ENERGY_NOW="0" | |
ENERGY_FULL="1" | |
continue | |
fi | |
printf '%s\n' "POWER_SUPPLY_$SUFFIX not found in $BAT/uevent" | |
fi | |
done >&2 | |
case "$STATUS" in | |
"Charging") ENERGY="$((ENERGY_FULL - ENERGY_NOW))" ;; | |
"Discharging"|"Not charging") ENERGY="$ENERGY_NOW" ;; | |
*) ;; | |
esac | |
printf '%s %s' "${BAT##*/}" "$STATUS" | |
printf ' %d%%' "$((100 * ENERGY_NOW / ENERGY_FULL))" | |
if [ -n "$ENERGY" ] && [ "$POWER_NOW" -gt "0" ]; then | |
REMAINING="$((3600 * ENERGY / POWER_NOW))" | |
SECS="$((REMAINING % 60))" | |
MINS="$(((REMAINING / 60) % 60))" | |
HOURS="$((REMAINING / 3600))" | |
printf ' %02d:%02d:%02d' "$HOURS" "$MINS" "$SECS" | |
[ "$STATUS" = "Charging" ] \ | |
&& printf ' until charged' \ | |
|| printf ' remaining' | |
fi | |
printf '\n' | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment