dotfiles

My personal shell configs and stuff
git clone git://git.alex.balgavy.eu/dotfiles.git
Log | Files | Refs | Submodules | README | LICENSE

battery (1667B)


      1 #!/bin/sh
      2 # Cross-platform battery information script
      3 # With no arguments, prints battery percentage and power source, separated by newline
      4 
      5 os=$(uname -s | tr '[:upper:]' '[:lower:]')
      6 case "$os" in
      7   linux*)
      8     state="$(cat /sys/class/power_supply/BAT0/status)"
      9     percent="$(cat /sys/class/power_supply/BAT0/capacity)"
     10     ;;
     11   darwin*)
     12     battstatus="$(pmset -g batt)"
     13     percent="$(printf "%s" "$battstatus" | awk '/InternalBattery/ { print $3 }' | tr -d '%;')"
     14     if { printf "%s" "$battstatus" | grep -q "from 'Battery Power'"; }; then state="battery";
     15     elif { printf "%s" "$battstatus" | grep -q "from 'AC Power'"; }; then state="charging";
     16     else printf "Could not determine state.\n" >&2; exit 1; fi
     17     ;;
     18   msys*|cygwin*|mingw*|nt|win*)
     19     printf "Windows not yet supported.\n" >&2
     20     exit 1
     21     ;;
     22   *)
     23     printf "Operating system %s is unknown.\n" "$os" >&2
     24     exit 1
     25     ;;
     26 esac
     27 
     28 while [ $(($#)) -ne 0 ]; do
     29   case "$1" in
     30     -p|--percent)
     31       printf "%s" "$percent"
     32       exit 0
     33       ;;
     34     -s|--state)
     35       printf "%s" "$state"
     36       exit 0
     37       ;;
     38     -h|--help)
     39       echo "Usage: $0 [options]"
     40       echo "Print information about the battery. Without any options, prints percent and state, on separate lines."
     41       echo "Options:"
     42       echo "-p      percent"
     43       echo "-s      state (charging or battery)"
     44       echo "-h      print this help text"
     45       exit 0
     46       ;;
     47     --) # end arg parsing
     48       shift
     49       break
     50       ;;
     51     -*) # unsupported flags
     52       echo "Unsupported flag $1" >&2
     53       exit 1
     54       ;;
     55     *) # preserve positional arguments
     56       break
     57       ;;
     58   esac
     59 done
     60 printf "%s\n%s" "$percent" "$state"