I want to run top is batch / non-interactive mode with -b. However I want the output sorted by PID. What command line option does this? I'm using Debian Lenny and the -o pid option from here ( http://www.unixtop.org/man.shtml ) doesn't work.

link|improve this question

79% accept rate
On my local Ubuntu system, this appears to be default behavior. I ran top -b -n1 and it was sorted by ascending pid. I also do not seem to have the -o option. – Kyle Smith Jan 20 '11 at 14:22
My systems (Debian, Ubuntu, and RHEL) sort by PID by default as well. Are you sure you don't have a config file (/etc/toprc or ~/.toprc) changing the default? – Cakemox Jan 20 '11 at 14:40
That man page seems to document the BSD version of top rather than the GNU version. Since it mentions Linux, it would seem to imply that Linux versions support the -o option. Perhaps there is a Linux port of the BSD version. – Dennis Williamson Jan 20 '11 at 15:57
feedback

2 Answers

For me, on an Ubuntu system, with no ~/.toprc or /etc/toprc running top 3.2.8, The primary sort is %CPU and the secondary sort is PID.

To set up top to sort by PID for batch mode:

If you don't have a ~/.toprc to begin with:

  • Start top in interactive mode.
  • Press W. That will write a new ~/.toprc with the current settings.
  • Exit top (press q).

To create the necessary configuration files:

  • Make a backup copy of your ~/.toprc file. You will need this for a later step. Let's call this file ~/.toprc.ORIG (you can choose another name if you prefer).
  • Start top in interactive mode.
  • Press F, then a, then Enter. That will select PID as the sort field.
  • Press R. That will reverse the sort so it's ascending.
  • Press W. That will write a new ~/.toprc with the current settings.
  • Exit top (press q).
  • mv ~/.toprc ~/toprc.PIDSORT (or choose a name you prefer)
  • Copy the backup back to the original (cp ~/.toprc.ORIG ~/.toprc).

To use the file you created to output top -b -n1 sorted by PID, create a script like this:

#!/bin/bash
cp "$HOME/.toprc.PIDSORT" "$HOME/.toprc"
top -b -n1 > /path/to/outputfile
cp "$HOME/.toprc.ORIG" "$HOME/.toprc"
link|improve this answer
feedback

You could try running the output through sort e.g.

top -b -n1 | sort -b -n

That sorts the default output numerically and therefore by PID. It does though mangle the order of the header lines.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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