Sorting ps output

By default, the ps command output is unsorted. The -sort parameter forces ps to sort the output. The ascending or descending order can be specified by adding the + (ascending) or - (descending) prefix to the parameter:

$ ps [OPTIONS] --sort -paramter1,+parameter2,parameter3..

For example, to list the top five CPU-consuming processes, use the following:

$ ps -eo comm,pcpu --sort -pcpu | head -5
COMMAND         %CPU
Xorg             0.1
hald-addon-stor  0.0
ata/0            0.0
scsi_eh_0        0.0

This displays the top five processes, sorted in descending order by percentage of CPU usage.

The grep command can filter the ps output. To report only those Bash processes that are currently running, use the following:

$ ps -eo comm,pid,pcpu,pmem | grep bash
bash ...

Get Linux Shell Scripting Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.