Skip to content

Instantly share code, notes, and snippets.

@daniel-santos
Last active September 24, 2025 20:34
Show Gist options
  • Select an option

  • Save daniel-santos/0a7219e0765e2078eaa888a2f80d7687 to your computer and use it in GitHub Desktop.

Select an option

Save daniel-santos/0a7219e0765e2078eaa888a2f80d7687 to your computer and use it in GitHub Desktop.
Show total memory and swap for all processes matching a pattern, e.g. `procmem firefox`
#!/bin/bash
pat="$1"
pids=$(
find /proc/* -maxdepth 1 -name exe -printf "%p\t%l\n" 2>&- \
| grep "$pat" \
| perl -pe 's|^/proc/(\d+)/exe.*$|$1,|g;' \
| tr -d \\n
)
status=$(mktemp -p /tmp procmem.XXXXXXXX)
eval cat /proc/{${pids%,}}/status > $status 2>/dev/null
rssize=$(grep VmRSS $status | awk '{print $2 "+"}' | tr -d \\n)
vmsize=$(grep VmSize $status | awk '{print $2 "+"}' | tr -d \\n)
vmswap=$(grep VmSwap $status | awk '{print $2 "+"}' | tr -d \\n)
to_human_num() {
local suf=KiB
local val=$1 || return 1
local ival=$(echo "scale=0; $val / 1" | bc -l)
if (( ival > 1024 )); then
val=$(echo "$val / 1024" | bc -l)
ival=$(echo "scale=0; $val / 1" | bc -l)
suf=MiB
fi
if (( ival > 1024 )); then
val=$(echo "$val / 1024" | bc -l)
ival=$(echo "scale=0; $val / 1" | bc -l)
suf=GiB
fi
if (( ival > 1024 )); then
val=$(echo "$val / 1024" | bc -l)
ival=$(echo "scale=0; $val / 1" | bc -l)
suf=TiB
fi
local fmt
if (( ival < 10 )); then
fmt="%3.2f"
elif (( ival < 100 )); then
fmt="%3.1f"
else
fmt="%3.0f"
fi
printf "${fmt}%s" "$val" ${suf::1}
}
printf "rss\tvmswap\ttotal\tprocess\n"
printf "%s\t%s\t%s\t%s\t%s\n" \
$(to_human_num $(echo "${rssize%+}" | bc -l)) \
$(to_human_num $(echo "${vmswap%+}" | bc -l)) \
$(to_human_num $(echo "${rssize%+}+${vmswap%+}" | bc -l)) \
"$pat"
rm $status
@daniel-santos
Copy link
Author

daniel-santos commented Sep 24, 2025

This is a little bash script I wrote to quickly see how much memory my browser is using, as it will have many processes. It might work under sh, but I haven't tested it. It expects a Linux /proc file system and requires find, awk, perl, bc, grep, and tr. Yes, the whole thing could be rewritten as a perl script, C program or whatever, but here it is.

$ procmem firefox-bin
rss     vmswap  total   process
6.13G   1.87G   8.00G   firefox-bin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment