Linux – Debian – top(1) in batch mode, but sorted by PID

debianlinuxmonitoringtop

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.

Best Answer

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"