Skip to content

Instantly share code, notes, and snippets.

@jdowning
Created May 28, 2014 20:08
Show Gist options
  • Save jdowning/3844277eb184cfa988c6 to your computer and use it in GitHub Desktop.
Save jdowning/3844277eb184cfa988c6 to your computer and use it in GitHub Desktop.
Swappy :: Calculate swap usage for each PID in Linux
#!/usr/bin/env bash
## Usage: swappy [-t|--total]
## Identify the processes that use swap
# Usage
test "$1" = "-h" -o "$1" = "--help" && {
grep '^##' <"$0" | cut -c4-
exit 2
}
# Color check
if [ -t 1 ]; then
ncolors=`tput colors`
if test -n "$ncolors" && test $ncolors -ge 8; then
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 4`
CYAN=`tput setaf 6`
RESET=`tput sgr0`
fi
fi
# Main
total_swap=0
printf "%-8b %8b %-b\n" "${MAGENTA}PID" "SWAP" "CMD${RESET}"
for pid in $(ls -d /proc/*/smaps| cut -f3 -d'/' | egrep '[0-9]+$'); do
pid_cmd=$(cat /proc/$pid/cmdline 2>/dev/null|tr '' ' ')
pid_swap=$(awk 'BEGIN{total=0}/Swap/{total+=$2}END{print total}' /proc/$pid/smaps 2>/dev/null)
if [ "$pid_swap" != '' ] && [ "$pid_swap" -gt 0 ]; then
printf "%-8d %6d KB %-s\n" "$pid" "$pid_swap" "$pid_cmd"
let total_swap+=$pid_swap
fi
done
if [ "$1" = "-t" -o "$1" = "--total" ]; then
printf "Total: %4b KB\n" "${RED}${total_swap}${RESET}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment