简体   繁体   中英

How can I manipulate a specific output in Bash (uptime)?

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!

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

This might be a way using just uptime, date and of course bash:

#!/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))

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

Using your output into a file named date, i tried this :

cat date | awk '{print $1 " "  $2 " "  0 ":"  $3  "," $5 " " $6 " " $7 " " $8 " " $9 " " $10 " " $11}'

21:08:13 up 0:10,4 users, load average: 0.30, 0.30, 0.25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM