11.8. Uptime
As with load, the data available through uptime is very
difficult to parse. Again, if you have the /proc/ filesystem, take advantage of it. I
wrote the following code to output just the time the system has been up:
#!/bin/bash
#
# upt - show just the system uptime, days, hours, and minutes
let upSeconds="$(cat /proc/uptime) && echo ${temp%%.*})"
let secs=$((${upSeconds}%60))
let mins=$((${upSeconds}/60%60))
let hours=$((${upSeconds}/3600%24))
let days=$((${upSeconds}/86400))
if [ "${days}" -ne "0" ]
then
echo -n "${days}d"
fi
echo -n "${hours}h${mins}m" |
Output looks like "1h31m" if the system has been up less than a day, or
"14d17h3m" if it has been up more than a day. You can massage the output
to look the way you want it to. This evolved after an e-mail discussion
with David Osolkowski, who gave me some ideas.
Before I wrote that script, I had a couple emails with David O, who said
"me and a couple guys got on irc and started hacking with sed and
got this:
uptime | sed -e 's/.* \(.* days,\)\? \(.*:..,\) .*/\1 \2/' -e's/,//g' -e 's/ days/d/' -e 's/ up //'.
It's ugly, and doesn't use regex nearly as well as it should, but it
works. It's pretty slow on a P75, though, so I removed it."
Considering how much uptime output varies depending on
how long a system has been up, I was impressed they managed as well as they
did. You can use this on systems without
/proc/ filesystem, but as he says, it
may be slow.
Relative speed: the "upt" script takes about 0.68 seconds on an unloaded
486SX25 (half that as a function). Contrary to David's guess, his use of
sed to parse the output of "uptime" takes only 0.22 seconds.