source code of /small-scripts/stackexchange/uptimerecord

Last modified
Lines 48

Parent directory Download CGIread sitemap Main page

Quick links: (none)

  1. #!/bin/sh
  2. format_time ()
  3. {
  4.     t=$1
  5.     days=$(($t / 86400))
  6.     t=$(($t - 86400*$days))
  7.     hours=$(($t / 3600))
  8.     t=$(($t - 3600*$hours))
  9.     minutes=$(($t / 60))
  10.     t=$(($t - 60*$minutes))
  11.     echo "$days days $hours hours $minutes minutes $t seconds"
  12. }
  13. main ()
  14. {
  15.     record_file="$1"
  16.     # Old record
  17.     record="$(cat "$record_file")"
  18.     # When the system started.
  19.     boot="$(date -d "$(uptime -s)" '+%s')"
  20.     while true; do
  21.         # You could also calculate the uptime before the loop and just
  22.         # increment it, but that will rely on the script running 24/7.
  23.         now="$(date '+%s')"
  24.         current_uptime="$(($now - $boot))"
  25.         # Set and save the record when it gets beaten
  26.         if [ "$current_uptime" -gt "$record" ]; then
  27.             record="$current_uptime"
  28.             echo "$record" > "$record_file"
  29.         fi
  30.         # Status should be printed _after_ potentially having set
  31.         # a new record:
  32.         clear
  33.         echo "Current uptime: $(format_time "$current_uptime")"
  34.         echo "Record uptime: $(format_time "$record")"
  35.         # Don't waste system resources for silly things.
  36.         sleep 1
  37.     done
  38. }
  39. main ~/uptimerecord.data