Question

To an idea of CPU load average, I'm using uptime in a ksh script:

uptime | awk '{print $11}' | sed '$s/.$//' | read CPU

where I then use the variable CPU later.

The $11 part is to isolate the last five minutes part. But, I noticed today that this was not working. Specifically, the last five minutes part was returned with $9. The function is returning less parameters. This is because the machine was recently rebooted, and so uptime shows minutes since reboot instead of days and minutes.

Is there a way I can consistently get only the last five minutes part of uptime?

Was it helpful?

Solution

Try to split away the text before "Load Average", and then use awk on the remaining part.

uptime | sed 's/.*load average: //' | awk -F\, '{print $2}'

OTHER TIPS

cut -d ' ' -f2 /proc/loadavg

/proc/loadvg is the source of data for uptime, w, who and others. It has a simpler format and the numbers always have a dot before the decimal part (uptime and such use the current locale, so you may find something like

load average: 0,18, 0,26, 0,30

which are harder to parse

plus is faster by an incredibly low factor! ;-)

It might be simpler to read the 2nd to last field rather than the 9th or the 11th:

uptime | awk '{print $(NF-1)}' FS=,

This little shell function should work with bash or ksh(93)

    function loadavg {
        typeset minutes=$1 t1=$(uptime)
        echo ${t1#*load average: } | (
            IFS=', ' && read L1 L5 L15
            case $minutes in
            (1)  echo $L1;;
            (5)  echo $L5;;
            (15) echo $L15;;
            ("") echo $L1 $L5 $L15;;
            (*)  echo "usage: loadavg [ 1 | 5 | 15 ]" 1>& 2
            esac                
        )
    }

Explanation:

This code uses IFS to split the string after "load average: " into three fields. 'typeset' and the subshell isolate the function variables from other shell variables.

The following simplifies the result, and just returns the answer to the original question:

function load5 {
    typeset t1=$(uptime)
    echo ${t1#*load average: } | (
        IFS=', ' && read L1 L5 L15
        echo $L5            
    )
}

This could give you best result I am using it to get my load average for every 5 minutes:

$ uptime | awk '{ print $11 }'| tr -d ','

So, I was having trouble writing one that worked in both Linux and Mac OS X. After much fighting I came up with this:

uptime | sed 's/.*load average[s]*://' | awk '{print $3}'

Hope this is helpful for someone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top