Bash – How to get the time when the system booted up in epoch format

bashlinuxshell-scriptuptime

I need to write a script that figures out if a reboot has occurred after an RPM has been installed. It is pretty easy to get the epoch time for when the RPM was installed: rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1, which produces output that looks like this: 1423807455.

This cross checks with rpm -q --info.

# date -d@`rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1`
Fri Feb 13 01:04:15 EST 2015
# sudo rpm -q --info glibc | grep "Install Date" | head -1
Install Date: Fri 13 Feb 2015 01:04:15 AM EST      Build Host: x86-022.build.eng.bos.redhat.com

But I am getting stumped on trying to figure out how to get the epoch time from uptime or from cat /proc/uptime. I do not understand the output from cat /proc/uptime which on my system looks like this: 19496864.99 18606757.86. Why is there two values? Which should I use and why do these numbers have a decimal in them?

UPDATE: thanks techraf

here is the script that I will use …

#!/bin/sh

now=`date +'%s'`
rpm_install_date_epoch=`rpm -q --queryformat "%{INSTALLTIME}\n" glibc | head -1`
installed_seconds_ago=`expr $now - $rpm_install_date_epoch`
uptime_epoch=`cat /proc/uptime | cut -f1 -d'.'`

if [ $installed_seconds_ago -gt $uptime_epoch ]
then
        echo "no need to reboot"
else
        echo "need to reboot"
fi

I'd appreciate any feedback on the script.

Thanks

Best Answer

As manuals (and even Wikipedia) point out:

/proc/uptime

Shows how long the system has been on since it was last restarted.

The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds. On multi core systems (and some linux versions) the second number is the sum of the idle time accumulated by each CPU.

The decimal point separates seconds from fractions of a second. To calculate point in time system booted up using this metrics, you would have to subtract the number of of seconds the system has been up (first number) from current time in epoch format rounding up the fraction.

Related Question