1

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.

Steven Monday
  • 13,599
  • 4
  • 36
  • 45
Amandasaurus
  • 31,471
  • 65
  • 192
  • 253
  • 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

2 Answers2

4

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"
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
0

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.

user9517
  • 115,471
  • 20
  • 215
  • 297