Skip to content
Advertisement

How to capture the output of a top command (for a specific process that will die) in a file

I have a process MYPID=18686 that I am monitoring with top.

top -b -n 1000 -d 5 -p $MYPID | tail -1 > log.txt

When the process dies, the output file is empty.

My end goal is just to record cpu usage over the lifetime of that process. Specifying -n 1000 -d 5 is a cheap workaround that runs top for the expected lifetime of the process. The tail -1 was to eliminate continually recording the top headers.

The answers to this question were helpful, but not a solution. How to capture the output of a top command in a file in linux?

Advertisement

Answer

tail -1 does not produce the last line of each screen of output that top produces. It produces only the last line of all the lines.

Try:

top -b -n 1000 -d 5 -p "$MYPID" | grep "$MYPID" > log.txt

This will collect into log.txt all the lines that mention the PID but none of the headers (assuming the PID doesn’t appear on a header).

Note that grep is usually buffered. This means that, if you check on log.txt during a run, it might be out of date. With GNU grep, you can keep log.txt up to date with the --line-buffered option:

top -b -n 1000 -d 5 -p "$MYPID" | grep --line-buffered "$MYPID" > log.txt
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement