Objective: List running processes on Linux and sort them by memory usage.
To view running processes, we use the ps command. To list processes together with memory utilisation / usage, run ps command with the following syntax.
| 1 | $ ps aux | 
To sort the processes according to memory usage, I was initially using the following syntax, which is the wrong way.
| 1 2 3 4 5 6 | $ ps aux | sort -nrk 4 root      2322  0.0  6.3  51132 16072 tty7     Ss+  14:29   0:00 /usr/bin/Xorg :0 -br -verbose -novtswitch -auth /var/run/gdm3/auth-for-Debian-gdm-HF0ZwT/database -nolisten tcp vt7 123       2794  0.0  6.0  56528 15236 ?        Sl   14:29   0:00 /usr/lib/gdm3/gdm-simple-greeter 123       2667  0.0  5.5 141436 14008 ?        Sl   14:29   0:00 /usr/lib/gnome-settings-daemon/gnome-settings-daemon 123       2791  0.0  4.0  52784 10160 ?        Sl   14:29   0:00 metacity 123       2620  0.0  3.5  49200  9064 ?        Ssl  14:29   0:00 /usr/bin/gnome-session -f --start /usr/share/gdm/greeter/autostart --debug | 
The output of ps is sorted based on the 4th field (memory usage field). Note that the header field is no longer available.
The proper way to sort based on memory usage is by using the following syntax. Processes with the largest RSS sizes will be at the top.
| 1 2 3 4 5 6 7 | $ ps aux --sort -rss USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND root      2322  0.0  6.3  51132 16072 tty7     Ss+  14:29   0:00 /usr/bin/Xorg :0 -br -verbose -novtswitch -auth /var/run/gdm3/auth-for-Debian-gdm-HF0ZwT/data 123       2794  0.0  6.0  56528 15236 ?        Sl   14:29   0:00 /usr/lib/gdm3/gdm-simple-greeter 123       2667  0.0  5.5 141436 14008 ?        Sl   14:29   0:00 /usr/lib/gnome-settings-daemon/gnome-settings-daemon 123       2791  0.0  4.0  52784 10160 ?        Sl   14:29   0:00 metacity 123       2620  0.0  3.5  49200  9064 ?        Ssl  14:29   0:00 /usr/bin/gnome-session -f --start /usr/share/gdm/greeter/autostart --debug | 
To sort in reverse order, that is to print processes with the largest RSS value at the bottom, use the following syntax. The “-rss” option has to be replaced with “rss“.
| 1 2 3 4 5 6 7 | $ ps aux --sort rss USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND root         2  0.0  0.0      0     0 ?        S    14:29   0:00 [kthreadd] root         3  0.0  0.0      0     0 ?        S    14:29   0:00 [ksoftirqd/0] root         5  0.0  0.0      0     0 ?        S<   14:29   0:00 [kworker/0:0H] root         6  0.0  0.0      0     0 ?        S    14:29   0:00 [kworker/u2:0] root         7  0.0  0.0      0     0 ?        S    14:29   0:00 [rcu_sched] | 

