I am trying to have a terminal showing the last 5 processes opened. This is helpful for my debugging.

At this point I have

watch ps -ef --sort=start_time

This works fine but it shows all processes so they don't fit in the screen. How can I limit it to a specific number like 5 or 10?

-- Update --

A have tried

watch "ps -ef --sort=start_time | tail -n 5"

but the problem is that the header of ps is omitted so after a while I don't know what I am looking at.

  • watch ps -ef --sort=start_time | head -5 or watch ps -ef --sort=start_time | tail -5 depending on whether the sort is ascending or not – mnmnc Jul 23 '14 at 9:45

You want:

watch "ps -ef --sort=start_time | tail -n 5"

tail will only output the last n lines piped to it.

I assume you tried:

watch ps -ef --sort=start_time | tail -n 5

Which would try and pipe the output of watch to tail, rather than the output of ps, and as watch never terminates, tail can't determine when the last n lines are output, so also prints nothing.

If you wish to keep the header as well, you can use some clever bash to simply:

watch "ps -ef --sort=start_time | (head -n 1 ; tail -n 5)"

Which causes head to print the top line as well.

  • I tried this. The problem is that the header line is then omitted. Would prefer if I could keep the header.. – Pithikos Jul 23 '14 at 9:51
  • Apologies, I fell into the exact pitfall I mentioned in the middle of my post, try now! – Andrew Stubbs Jul 23 '14 at 10:01
  • 1
    The combination of head and tail on a single pipe does not work reliably, but only if the ps output is longer than head's input buffer (try watch "ps -f --sort=start_time | (head -n 1 ; tail -n 5)" to see what I mean). To make sure that both programs see all the output, you need to use a temporary file, eg watch "ps -ef --sort=start_time >TempFile; head -n 1 <TempFile ; tail -n 5 <TempFile" (you could also use tee to create tempFile). Both -f and -ef now show the last five lines. – AFH Jul 23 '14 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.