sort ps output in Ubuntu

We have already covered how to list processes with ps command in Ubuntu. When we run ps aux command, it shows us the output or processes sorted by their Process IDs by default. But, what if we want to know the process which is using the maximum amount of memory. In that case, either we see the output ourselves or just sort it. Exploring the output manually is not the efficient path. So, in this article, we would cover how we can sort ps output in Ubuntu.

ps command mainly shows us the information about current running processes. It isn’t updated real-time. So, we need to run the ps command every time we need the latest data about processes.

We need to first see what all headers are there when we run the ps command and sort the output accordingly. We are using ps aux for simplicity here. You can use other command-options. This is just for illustration.

ps aux

The header row for the above would be –

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

Since, we sort on the basis of a header. Therefore, it is necessary to know the header we sort. For instance, we want to sort the output according to the VSZ usage. Apart from that, we should also decide the order of the output – ascending or descending.

sort ps output in Ubuntu

If its ascending order (i.e. lowest first) sort, then –

ps aux --sort=vsz

But, if its descending order sort, then negative sign () precedes vsz

ps aux --sort=-vsz

Besides, what if we want output from specific headers and sort one them. Then, use -eo option. -e option is for all running processes and -o is for headers. This is how it goes –

ps -eo pid,user,vsz,rss,comm --sort=rss

Lastly, what about %MEM and %CPU headers. If we issue the following –

ps aux --sort=%MEM

It will throw an error –

error: unknown sort specifier

So, we need to use p in place of % in the above code to get the desired result –

ps aux --sort=pmem

Similarly, for %CPU

ps aux --sort=pcpu

In conclusion, we have discussed how to sort ps command output in Ubuntu.

Similar Posts