Skip to content

Instantly share code, notes, and snippets.

@Juul
Created January 20, 2020 05:17
Show Gist options
  • Save Juul/6cede1bbb2d3ef8fb66ae7343173ed06 to your computer and use it in GitHub Desktop.
Save Juul/6cede1bbb2d3ef8fb66ae7343173ed06 to your computer and use it in GitHub Desktop.
Show total combined memory usage (virtual, resident and dirty) for processes matching the given grep arguments
#!/bin/bash
# Show total memory usage of all processes matching the supplied grep arguments
if [ "$#" -lt "1" ]; then
echo "Usage: $0 <grep arguments>" >&2
exit 1
fi
function humanize() {
val=$1
if [ "$val" -gt "1024" ]; then
val=`bc <<< "scale=2; ${val}/1024"`
echo "$val MB"
return
fi
echo "$val kB"
}
virtual=0
resident=0
dirty=0
while IFS= read -r pid; do
# echo "$pid"
mem=$(pmap -x "$pid" | grep total)
virt=`echo $mem | awk '{print $3}'`
if [ ! -z "$virt" ]; then
virtual=$(($virtual + $virt))
fi
res=`echo $mem | awk '{print $4}'`
if [ ! -z "$res" ]; then
resident=$(($resident + $res))
fi
dirt=`echo $mem | awk '{print $5}'`
if [ ! -z "$dirt" ]; then
dirty=$(($dirty + $dirt))
fi
done < <(ps aux | grep $@ | grep -v grep | awk '{print $2}')
virtual=$(humanize $virtual)
resident=$(humanize $resident)
dirty=$(humanize $dirty)
printf '%s %16s\n' "Virtual " "$virtual"
printf '%s %16s\n' "Resident" "$resident"
printf '%s %16s\n' "Dirty " "$dirty"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment