Search code examples
linuxbashshelluptime

Extract the uptime value from "w" command output


How can I get the value of up from below command on linux?

# w
 01:16:08 up 20:29,  1 user,  load average: 0.50, 0.34, 0.30
USER     TTY        LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0     00:57    0.00s  0.11s  0.02s w

# w | grep up
 01:16:17 up 20:29,  1 user,  load average: 0.42, 0.33, 0.29

Solution

  • Given that the format of the uptime depends on whether it is less or more than 24 hours, the best I could come up with is a double awk:

    $ w
     18:35:23 up 18 days, 9:08, 6 users,...
    $ w | awk -F 'user|up ' 'NF > 1 {print $2}' \
        | awk -F ','       '{for(i = 1; i < NF; i++) {printf("%s ",$i)}} END{print ""}'
    18 days   9:08