Detecting the First Boot of the Year

With the arrival of a new calendar year an interesting thought problem taunted — how to detect the first boot in a new calendar year?

Many people use computers daily and the point might be irrelevant. What happens with an extended shutdown period? For example, the computer is powered off from December 15 to January 15? The extended period might skip certain cron jobs executed at the beginning of the year. There are tools such as anacron that might help but life is full of holes.

Perhaps the last command can help using the -F option.


    YEAR_CURRENT=$(date +%Y)
    YEAR_PREVIOUS=$(($YEAR_CURRENT - 1))
    echo "The current year: $YEAR_CURRENT"
    echo "The previous year: $YEAR_PREVIOUS"
    BOOT_CURRENT="$(last -F | grep reboot | sed ’s| - .*||’ | head -n1)"
    BOOT_PREVIOUS="$(last -F | grep reboot | sed ’s| - .*||’ | head -n2 | tail -n1)"
    if [ "$BOOT_CURRENT" = "" ]; then
      # Perhaps the logs were rotated.
      BOOT_CURRENT="$(last -F -f /var/log/wtmp.1 | grep reboot | sed ’s| - .*||’ | head -n1)"
      BOOT_PREVIOUS="$(last -F -f /var/log/wtmp.1 | grep reboot | sed ’s| - .*||’ | head -n2 | tail -n1)"
    fi
    if [ "$(echo $BOOT_CURRENT | grep $YEAR_CURRENT)" != "" ]; then
      echo "The current boot occurred in $YEAR_CURRENT"
    elif [ "$(echo $BOOT_CURRENT | grep $YEAR_PREVIOUS)" != "" ]; then
      echo "The current boot occurred in $YEAR_PREVIOUS"
    fi
    if [ "$(echo $BOOT_PREVIOUS | grep $YEAR_PREVIOUS)" != "" ]; then
      echo "The previous boot occurred in $YEAR_PREVIOUS"
    elif [ "$(echo $BOOT_PREVIOUS | grep $YEAR_CURRENT)" != "" ]; then
      echo "The previous boot occurred in $YEAR_CURRENT"
    fi
    if [ "$(echo $BOOT_CURRENT | grep $YEAR_CURRENT)" != "" ] && \
       [ "$(echo $BOOT_PREVIOUS | grep $YEAR_PREVIOUS)" != "" ]; then
      echo "This is the first boot of the year"
    else
      echo "Not the first boot of the year"
    fi
    

Posted: Category: Usability Tagged: General

Next: Setting a System Wakeup Time

Previous: LPT1 Pass-Through