Home / Show only one process with top on Linux

Show only one process with top on Linux

Top is a useful command line tool for showing processes running on Linux (and other operating systems) such as how much CPU and memory they've been using and how long they've been running, and also showing the system load, CPU and memory usage as a whole. But what if you only one to show output for one process or command?

Use the -p flag to specify the pid

If you know the pid number of the process, use the -p flag to specify it:

top -p [pid]


top -p 1234

Combine with pidof if you don't know the pid

pidof will return the PIDs for the process that matches the input, so you can do this:

top -p `pidof [process name]`

The only problem with this is that if there's more than one process matching the name then it won't work, because you either have to specify each pid with another -p flag or comma separate the values, and you'll get an error like this, when trying to do top for just nginx:

$ top -p `pidof nginx`
	top: unknown option '1'
usage:	top -hv | -bcHiSs -d delay -n limit -u|U user | -p pid[,pid] -w [cols]

You can either use pidof's -s flag to return just one pid:

top -p `pidof -s nginx`

which isn't ideal, because you're only get one of them, or combine it with some sed magic to convert spaces between the ids returned from pidof with commas:

top -p `pidof [process name] | sed 's/ /,/g'`

Replace [process name] with the process, e.g. with nginx as shown in the next example:

top -p `pidof nginx | sed 's/ /,/g'`

Combine with pgrep to match a name

Another alternative to combining top with pidof is to use pgrep. This can be useful if you need to match e.g. a PHP script which is running from the command line and which you could only match 'php' when running pidof and might return something different from what you want.

(Note that there is a -x flag for pidof which the man page says "Scripts too – this causes the program to also return process id's of shells running the named scripts" but it didn't seem to work when I tried it myself.)

If the script is called e.g. "myscript.php" you can do this:

top -p `pgrep -f myscript.php`

Again this will cause an error if it returns more than one pid. The output from pgrep will be have each pid on a new line, so we need to use tr to replace the newlines with commas and then sed to remove the final comma. If anyone has a tidier way of doing this, then please let me know in the comments.

top -p `pgrep -f myscript.php | tr 'n' , | sed s/,$//`
top -p `pgrep -f nginx | tr 'n' , | sed s/,$//`

And because pgrep does regular expression pattern matching, you can do all sorts of things with it, but note that there's a limit of 20 pids.

top: pid limit (20) exceeded

Oops, you can't pass any more than 20 pids to top.

You could combine the output of pidof or pgrep with "head -n 20"…