Determine what’s using swap space on linux

I found this useful shell script on a website a while back; works perfectly:

#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011
# Modified by Mikko Rantalainen 2012-08-09
# Pipe the output to "sort -nk3" to get sorted output
SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"`
do
PID=`echo $DIR | cut -d / -f 3`
PROGNAME=`ps -p $PID -o comm --no-headers`
for SWAP in `grep Swap $DIR/smaps 2>/dev/null | awk '{ print $2 }'`
do
let SUM=$SUM+$SWAP
done
if (( $SUM > 0 )); then
echo "PID=$PID swapped $SUM KB ($PROGNAME)"
fi
let OVERALL=$OVERALL+$SUM
SUM=0
done
echo "Overall swap used: $OVERALL KB"

The output will look like this:

PID=1 swapped 100 KB (init)
PID=479 swapped 652 KB (udevd)
PID=816 swapped 408 KB (udevd)
PID=1152 swapped 380 KB (vmtoolsd)
PID=1247 swapped 92 KB (portreserve)
PID=1254 swapped 292 KB (rsyslogd)
PID=1887 swapped 132 KB (xinetd)
PID=1926 swapped 264 KB (crond)
PID=2039 swapped 72 KB (mingetty)
PID=2041 swapped 76 KB (mingetty)
PID=2043 swapped 648 KB (udevd)
PID=2044 swapped 76 KB (mingetty)
PID=2046 swapped 72 KB (mingetty)
PID=2048 swapped 76 KB (mingetty)
PID=2050 swapped 72 KB (mingetty)
PID=2625 swapped 16116 KB (httpd)
PID=3086 swapped 5596 KB (named)
PID=3569 swapped 104 KB (couriertcpd)
PID=3571 swapped 28 KB (courierlogger)
PID=3579 swapped 96 KB (couriertcpd)
PID=3581 swapped 32 KB (courierlogger)
PID=3587 swapped 88 KB (couriertcpd)
PID=3589 swapped 16 KB (courierlogger)
PID=3596 swapped 88 KB (couriertcpd)
PID=3598 swapped 28 KB (courierlogger)
PID=3782 swapped 16108 KB (httpd)
PID=7994 swapped 16108 KB (httpd)
PID=9076 swapped 192 KB (mysqld_safe)
PID=9205 swapped 300 KB (mysqld)
PID=9719 swapped 16108 KB (httpd)
PID=9723 swapped 16108 KB (httpd)
PID=10019 swapped 16108 KB (httpd)
PID=10021 swapped 16108 KB (httpd)
PID=11713 swapped 16108 KB (httpd)
PID=11935 swapped 16108 KB (httpd)
PID=11938 swapped 16108 KB (httpd)
PID=11943 swapped 16108 KB (httpd)
PID=12101 swapped 16108 KB (httpd)
PID=12435 swapped 456 KB (master)
PID=12447 swapped 328 KB (qmgr)
PID=12698 swapped 416 KB (tlsmgr)
PID=12803 swapped 16108 KB (httpd)
PID=12818 swapped 16108 KB (httpd)
PID=12822 swapped 16108 KB (httpd)
PID=12824 swapped 16108 KB (httpd)
PID=13757 swapped 16108 KB (httpd)
PID=14248 swapped 16108 KB (httpd)
PID=14251 swapped 16108 KB (httpd)
PID=14252 swapped 16108 KB (httpd)
PID=14254 swapped 16108 KB (httpd)
PID=14255 swapped 16108 KB (httpd)
PID=14256 swapped 16108 KB (httpd)
PID=14257 swapped 16108 KB (httpd)
PID=17372 swapped 536 KB (sshd)
Overall swap used: 400712 KB

Leave a Reply

Your email address will not be published.