Skip to content

Instantly share code, notes, and snippets.

@pabloazurduy
Last active January 8, 2026 22:55
Show Gist options
  • Select an option

  • Save pabloazurduy/cebf9642554c998afda0c50a18d47b26 to your computer and use it in GitHub Desktop.

Select an option

Save pabloazurduy/cebf9642554c998afda0c50a18d47b26 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Get total system memory
TOTAL_MEM=$(sysctl -n hw.memsize)
# 1. ps: Get data
# 2. awk1: Calculate sums and output raw data with "|" delimiter (PCT|MB|NAME)
# 3. sort: Sort numerically by the first column (PCT)
# 4. awk2: Format the table and add headers
ps -axo rss,command | awk -v total_mem=$(sysctl -n hw.memsize) '
NR == 1 { next }
{
rss = $1
# Get the full command path (everything after the first column)
cmd = substr($0, index($0,$2))
# Split path by "/" to find the component ending in .app
n = split(cmd, parts, "/")
name = parts[n] # Default to the executable name (last part)
for (i=1; i<=n; i++) {
if (parts[i] ~ /\.app$/) {
name = parts[i]
sub(/\.app$/, "", name) # Remove .app suffix
break
}
}
mem[name] += rss
}
END {
# output: PCT MB NAME (Numeric first guarantees correct sorting)
for (name in mem) {
pct = (mem[name] * 1024 / total_mem) * 100
mb = mem[name] / 1024
if (pct > 0.1) {
print pct, mb, name
}
}
}
' | sort -rn | awk '
BEGIN {
printf "%-30s %10s %9s\n", "APP / PROCESS", "MB USED", "% MEM"
print "----------------------------------------------------"
}
{
pct = $1
mb = $2
# Reconstruct name from $3 onwards to handle spaces like "Google Drive"
name = substr($0, index($0,$3))
# Truncate very long names to keep table aligned
if (length(name) > 25) name = substr(name, 1, 23) ".."
printf "%-30s %10.1f %8.2f%%\n", name, mb, pct
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment