Skip to content

Instantly share code, notes, and snippets.

@riyad
Last active Jan 10, 2022
Embed
What would you like to do?
List all processes and how much swap they use.
#!/bin/bash
#
# Riyad Preukschas <riyad@informatik.uni-bremen.de>
# License: Mozilla Public License 2.0
# SPDX-License-Identifier: MPL-2.0
#
# List all processes and how much swap they use.
# The output format is: "<swap used> : <pid> : <process name>"
#
# To get the top 10 processes using swap you can run:
# lsswap | sort -hr | head -n10
files=(/proc/*/status)
exec awk '
BEGINFILE {
# skip files that cannot be opened
if ( ERRNO != "" ) {
nextfile
}
}
/^VmSwap:/ {
vmswap = $2;
vmswap_unit = $3;
# force conversion to a number
vmswap += 0
# make units more human readable
if (vmswap_unit == "kB" && vmswap > 1000) {
vmswap /= 1000
vmswap_unit = "MB"
}
if (vmswap_unit == "MB" && vmswap > 1000) {
vmswap /= 1000
vmswap_unit = "GB"
}
}
/^Name:/ { name = $2 }
/^Pid:/ { pid = $2 }
ENDFILE {
# skip processes that cannot be swapped or are not using swap at all
if (length(vmswap) != 0 && vmswap != 0) {
printf "%1.1f%s : %d : %s\n", vmswap, vmswap_unit, pid, name
}
}
' "${files[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment