#!/bin/sh unset QUIET MILLIWATTS TOTAL BATTERY="ALL" printhelp () { printf "power_now: get the current power draw from the battery.\n" printf "\t-q) print only the number\n" printf "\t-m) use milliwatts instead of watts\n" printf "\t-t) use the total of all batteries\n" printf "\t-b X) use battery X\n" exit 1 } while getopts "b:mqt" o; do case "${o}" in q) QUIET="y" ;; m) MILLIWATTS="y" ;; t) TOTAL="y" BATTERY="ALL" ;; b) BATTERY="$OPTARG" ;; *) printhelp ;; esac done error () { printf "%s\n" "$@" exit 1 } #TOTALPOWER='0' case "$BATTERY" in "ALL") find /sys/class/power_supply -name 'BAT*' || error "Are there no batteries?" for battery in /sys/class/power_supply/BAT*; do battery="$(basename "$battery")" DIRNAME="/sys/class/power_supply/${battery}" if [ -f "${DIRNAME}/power_now" ]; then if [ -n "${MILLIWATTS}" ]; then POWER="$(awk '{print $1/1e3}' "${DIRNAME}/power_now" | head -1)" else POWER="$(awk '{print $1/1e6}' "${DIRNAME}/power_now" | head -1)" fi elif [ -f "${DIRNAME}/current_now" ]; then if [ -n "${MILLIWATTS}" ]; then POWER="$(cat "${DIRNAME}/current_now" "${DIRNAME}/voltage_now" | paste -d' ' -s | awk '{print $1*$2/1e9}' | head -1)" else POWER="$(cat "${DIRNAME}/current_now" "${DIRNAME}/voltage_now" | paste -d' ' -s | awk '{print $1*$2/1e12}' | head -1)" fi fi if [ -n "${TOTAL}" ]; then TOTALPOWER="$(echo "${TOTALPOWER}" "${POWER}" | awk '{print $1+$2}'| head -1)" else if [ -z "${QUIET}" ]; then printf "Power in %s is " "${battery}" fi printf "%s" "${POWER}" if [ -n "${MILLIWATTS}" ]; then echo " mW" else echo " W" fi fi done if [ -n "${TOTAL}" ]; then if [ -z "${QUIET}" ]; then printf "Total power is " fi printf "%s" "${TOTALPOWER}" if [ -n "${MILLIWATTS}" ]; then echo " mW" else echo " W" fi fi ;; *) DIRNAME="/sys/class/power_supply/${BATTERY}" [ -d "${DIRNAME}" ] || error "No such battery!" if [ -f "${DIRNAME}/power_now" ]; then if [ -n "${MILLIWATTS}" ]; then POWER="$(awk '{print $1/1e3}' "${DIRNAME}/power_now" | head -1)" else POWER="$(awk '{print $1/1e6}' "${DIRNAME}/power_now" | head -1)" fi elif [ -f "${DIRNAME}/current_now" ]; then if [ -n "${MILLIWATTS}" ]; then POWER="$(cat "${DIRNAME}/current_now" "${DIRNAME}/voltage_now" | paste -d' ' -s | awk '{print $1*$2/1e9}' | head -1)" else POWER="$(cat "${DIRNAME}/current_now" "${DIRNAME}/voltage_now" | paste -d' ' -s | awk '{print $1*$2/1e12}' | head -1)" fi fi if [ -z "${QUIET}" ]; then printf "Power in %s is " "${BATTERY}" fi printf "%s" "${POWER}" if [ -n "${MILLIWATTS}" ]; then echo " mW" else echo " W" fi ;; esac