#!/bin/sh # File: /usr/local/bin/on-battery-time.sh # Author: bgstack15 # Startdate: 2019-06-09 22:35 # Title: Report how long this system has been on battery or AC power # Package: on-battery-time # Purpose: # History: # Usage: # Reference: # https://stackoverflow.com/questions/12199631/convert-seconds-to-hours-minutes-seconds/18683834#18683834 # Improve: # Dependencies: # bc # date # the udev rules from 99-on-battery-time.rules # Documentation: OBT_INFILE=/var/log/battery.log # FUNCTIONS convertsecs() { _h=$( expr $1 / 3600 ) _m=$( expr $1 % 3600 / 60 ) _s=$( expr $1 % 60 ) printf "%02d:%02d:%02d\n" ${_h} ${_m} ${_s} } # learn most recent utility time last_utility_time="$( { tac "${OBT_INFILE}" | awk '/utility power/{print $2}' ; echo 0 ; } | head -n1 )" # learn most recent battery time last_battery_time="$( { tac "${OBT_INFILE}" | awk '/on battery/{print $2}' ; echo 0 ; } | head -n1 )" # learn current time OBT_current_time="$( date "+%s" )" if test ${last_utility_time} -ge ${last_battery_time} ; then OBT_last="${last_utility_time}" OBT_phrase="utility power" else OBT_last="${last_battery_time}" OBT_phrase="on battery" fi OBT_seconds="$( printf "%s-%s\n" "${OBT_current_time}" "${OBT_last}" | bc )" printf "%s seconds: %s\n" "${OBT_phrase}" "${OBT_seconds}" convertsecs "${OBT_seconds}"