Scripts: battery level and nicer uptime

Oct 16, '03 05:58:00PM

Contributed by: Anonymous

I found many scripts in my documents folder, and I found two which are great for text-mode logins, which I'm learning to get used to in case of the need for damage repair. One prints the uptime nicely, and the other gives the battery level.

Read the rest of the hint for the code snippets...

[robg adds: I cannot get the battery script to run on my PowerBook, but the uptime script works. If anyone has a fix for the battery script, please post it as a comment and I'll edit it into the original hint.]

Battery level:


#!/bin/bash                                             
                                                        
if [ -x /usr/sbin/ioreg ] ; then
  ioreg -p IODeviceTree -n "battery" -w 0 | \
  sed -ne '/| *{/,/| *}/ {
    s/^[ |]*//g
    /^[{}]/!p  
  }' | \                                          
  awk '/Battery/ {                                
    gsub("[{}()\"]","", $3)                 
    gsub(","," ",$3)                        
    split($3,ct," ")                        
    sub(".*=","",ct[4])                     
    sub(".*=","",ct[5])                     
    print("Battery:",100*ct[5]/ct[4],"%")   
  }'                                              
fi
Uptime:

#!/bin/bash

uptime \
| awk '{
  # chops off "up" and everything before it:
  sub(/.*up[ ]+/,"",$0)
  # chops off ", # users" and everything after it:       
  sub(/,[ ]+[0-9]+ user.*/,"",$0)
  # cleans up extra spaces, i think:    
  sub(/,/,"",$0)
  # obvious enough, prints the results                       
  print("Uptime:",$0)
}'
Save these into Textedit on the Desktop (for convenience) as batt.txt and up.txt, and then do:

-- If you don't have a bin directory, do this first:
% mkdir ~/bin

% mv ~/Desktop/batt.txt ~/bin/batt
% mv ~/Desktop/up.txt ~/bin/up
% chmod u+x ~/bin/batt
% chmod u+x ~/bin/up
Next, put this line in the setup files that you 'source' at login. For tsch, this can be either .tcshrc or .login; for bash either .bash_profile or .profile:

export PATH="$PATH:$HOME/bin"

Comments (10)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20030831032303722