Rate this page del.icio.us  Digg slashdot StumbleUpon

Tips and tricks: How do I capture the output of “top” to a file?

by the editorial team

The command top is a very useful tool to capture information about process running on Linux. Many times this information may need to be captured to a file. This can be done with the following command:

top -b -n1 > /tmp/top.txt

This will run top once write the output to a file and exit.

The command top can also be run so that it will give multiple reports. To run top 5 times and wait 5 seconds between each output the command would be:

top -b -n5 -d5 > /tmp/top.txt

4 responses to “Tips and tricks: How do I capture the output of “top” to a file?”

  1. Jim Campbell says:

    This is a very simple, but very helpful tip. Thanks!

  2. Saida do Top para um arquivo « Tecnologia Livre! says:

    […] Fonte: Red Hat Magazine […]

  3. mesrik says:

    Just to point out that you certainly can use pipes too.

    Here’s snippet from my quick radiusguard script that makes sure radiusd stays running and does not take more than 20% of the cpu.


    runlevel=$(who -r | sed ’s/.*run-level *\([3-5]\) .*$/\1/’)

    if [ $(chkconfig –list radiusd | grep -c “$runlevel:on”) -eq 1 ]; then
    # get radiusd cpu usage
    CPU_USAGE=$(top -b -n 1 |\
    awk ‘/^[0-9]+ radiusd/ { cpu = $9 }
    END { printf(”%i\n”, length(cpu) == 0 ? -1 : cpu); }’)
    export CPU_USAGE
    echo “$CPU_USAGE” >/var/tmp/radiusguard.last
    if [ $CPU_USAGE -eq -1 ]; then
    act ’service radiusd stop ; service radiusd start’
    else
    if [ $CPU_USAGE -ge 20 ]; then
    act ’service radiusd restart’
    fi
    fi
    fi

    act is a function that sends email on event including outputs of the commands run. Runlevel is checked against chkconfig so that it won’t run berzerk when startup script is intentionally disabled or similar situations.

    Needed that script before last upgrade with radius, it just was occationally acting a cpu hog or died mysterioysly. Cpu hogging was really bad, it rendered the LDAP service in the same host unuseable.

    Cheers,

    :-) riku

  4. vikas sharma says:

    This command is similar to ps command
    give ps -el > /usr/process.txt

Leave a reply