0

So I've been experimenting with Bash not too long ago, and I want to manipulate the output from the "uptime" command. I managed to change the output of up x minutes to 0:05 for example if the up time is 5 minutes, but the rest of the things disappear.

What method should I use to also display the time, the amount of users and its load average without affecting my current up time output.

This is the desired output: 21:08:13 up 0:10, 3 users, load average: 0.30, 0.30, 0.25

Any help would be appreciated!

#!/bin/bash

since="`uptime --since`"
start="`date --date "$since" '+%s'`"
now="`date '+%s'`"
sec=$((now-start))

days=$((sec/(60*60*24)))
sec=$((sec-days*(60*60*24)))

hr=$((sec/(60*60)))
sec=$((sec-hr*(60*60)))

min=$((sec/60))
sec=$((sec-min*60))

rest="$(uptime | perl -npe'{s/(.*,\s+)(\d+\s+user)/$2/}')"

printf "%d(days), %02d:%02d:%02d(hms), %s\n" $days $hr $min $sec "$rest"

CURRENT OUTPUT

0(days), 00:34:00(hms), 3 users, load average: 0.09, 0.14, 0.14

1 Answer 1

1

One of the ways is with Perl. This is just one line added and the printf line altered:

rest="$(uptime | perl -npe'{s/(.*,\s+)(\d+\s+user)/$2/}')"

printf "%d(days), %02d:%02d:%02d(hms), %s\n" $days $hr $min $sec "$rest"

Result:

 00:55:21 up 10 days,  2:38,  1 user,  load average: 0.05, 0.06, 0.07

Note there's one field still missing, compare:

$ ./uptime.bash
10(days), 02:45:06(hms), 1 user,  load average: 0.02, 0.03, 0.04
$ uptime
 01:02:10 up 10 days,  2:45,  1 user,  load average: 0.02, 0.03, 0.04
11
  • Your code doesn't work unfortunately. It only gives the following: "0(days), 00:00:00(hms)," Like literally 00000. But this still doesn't give me a clue/idea on how to fix my problem.
    – Genki.-
    Commented Jun 12, 2019 at 23:36
  • @Genki.- It needs all of the preceding lines from your question. I just posted what's changed.
    – user147505
    Commented Jun 12, 2019 at 23:38
  • Ohh woops, my bad. I'll give it a try @Tomasz
    – Genki.-
    Commented Jun 12, 2019 at 23:39
  • Yeah indeed, there is a difference with the 1st field. Is it changeable?
    – Genki.-
    Commented Jun 12, 2019 at 23:42
  • 1
    Ah nothing @Tomasz I think I fixed it, thanks for the help!
    – Genki.-
    Commented Jun 13, 2019 at 0:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .