How to display time elapsed since last system boot using "uptime"?

I want to display the time elapsed since last system boot using uptime, but I don't want it to display all that info. I just want to know how many hours passed since last system boot (i.e. : 18:17:59)

9 Answers

To get the time elapsed since last system boot in hh:mm:ss format, you can use:

awk '{print int($1/3600)":"int(($1%3600)/60)":"int($1%60)}' /proc/uptime

/proc/uptime pseudo-file contains two numbers:

  • The first number is how long the system has been up in seconds.
  • The second number is how much of that time the machine has spent idle in seconds.

So, using awk you can take firs number and convert it in hh:mm:ss format.

1

To get uptime in seconds:

awk '{print $1}' /proc/uptime

To get uptime in minutes:

 echo $(awk '{print $1}' /proc/uptime) / 60 | bc

To get uptime in hours:

 echo $(awk '{print $1}' /proc/uptime) / 3600 | bc

To get x digits of precision you can add scale=x, e.g. for x=2

echo "scale=2; $(awk '{print $1}' /proc/uptime) / 3600" | bc

Try this one:

uptime | awk '{ print $3 }'

In fact, it prints the third word of the line produced by uptime.

4

A trivial modification to show days:

awk '{print int($1/86400)"days "int($1%86400/3600)":"int(($1%3600)/60)":"int($1%60)}' /proc/uptime

This will format your output as 2 zero padding:

awk '{printf("%02d:%02d:%02d",int($1/3600),int($1/3600/60),int($1%60))}' /proc/uptime

As an addition to @realmoonstruck answer:

You could do this solely in awk which saves you one pipe and the subsequent call of bc.

To get the uptime in minutes:

awk '{print int($1)/60}' /proc/uptime

For simple metrics, I sometimes just want an INT of the hours:

#!/usr/bin/env -eux
upsince=$(date +%s -d "$(uptime -s)");
now=$(date +%s);
DIFF=$((now-upsince));
scale=2;
echo $((DIFF / 3600)))

NOTE: You could '+ 1' to round up to the nearest full hour

A further trivial modification for layout:

UPTIME_STR=$(awk '{print int($1/86400)"d "int($1%86400/3600)"h "int(($1%3600)/60)"m "int($1%60)"s"}' /proc/uptime)
echo "['$(date)'] Device Uptime:" $UPTIME_STR

Example Output:

['Mon Jan 17 22:41:32 SAST 2022'] Device Uptime: 0d 0h 10m 58s

awk '{printf( "%04d:%02d:%02d:%02d\n",int($1/86400) , int(($1%86400)/3600) , int(($1%3600)/60) , int($1%60) )}' /proc/uptime;

Format [dddd:hh:mm:ss]
Sample: 0122:05:14:03

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like