Skip to content

Show What's on Swap in Linux

November 6th, 2017 - ITTutorial(1 min)

If you find your machine running sluggish, it might be the case that you have too many things running and it’s hitting the swap. You can check how bad (or good) things are with htop, but it won’t tell you which process is sitting on swap. To find out, I’ve cooked up a tiny script:

for i in `ps -ax |cut -f1 -d' '`; do
    k=$(grep VmSwap /proc/${i}/status)
    u=$(ps -ax |grep "$i")
    echo "$i - $k - $u"
done

It will look in /proc/[PID]/status and get the VmSwap field. Then, it’ll print it out along with the PID and the command line (from ps -ax).

Note: This is a rather crude script and it’ll give some errors for processes which have finished between running the initial ps -ax in the loop and the other ones.

A one-liner variant is:

for i in `ps -ax |cut -f1 -d' '`; do k=$(grep VmSwap /proc/${i}/status); u=$(ps -ax |grep "$i"); echo "$i - $k - $u";done

…which you can then pipe to e.g. a file or another command for further processing. One example is:

for i in `ps -ax |cut -f1 -d' '`; do k=$(grep VmSwap /proc/${i}/status); u=$(ps -ax |grep "$i"); echo "$k - $i - $u";done |cut -f2- -d: |sort -n -r

Which gives me the processes occupying the most swap space first.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: