Search code examples
bashps

How to filter processes by MEM% in Bash?


I've been given an assignment to print processes that are using 'x%' or more memory every 10 seconds. The x% will come from an argument when executing the file.

(E.G. ./processes.sh 8 will print all processes using 8% or more memory every 10 seconds.)

I have no clue how to sort the processes by a specific memory parameter. I know how to sort the processes in ascending or descending order, just not how to print only the select processes that meet my criteria. Here's a snippet of my code:

processes()
{
while :
do
        date
        echo "Processes occupying $1% of memory: "
        ps -o pid,user,%mem ax|sort -n -b -k3 -r|pgrep -f1 "$1"
        sleep 10
done
}

processes $1

I thought pgrep might be able to do it, but I think I either formatted it wrong, or it just doesn't work.

Ideally, the output should look like this:

Processes occupying 8% or more memory:
11452 kelly1653 13.6%
93612 buckley0003 29.6%

Any hints for me? I'm really frustrated. Thanks in advance!


Solution

  • This should be all you need:

    ps --no-headers -o pid,user,%mem |
        awk -v "arg=$1" '$3 >= arg {print $0 "%"}' |
        sort -nk 3
    

    Use awk to select lines that have the third field value your argument or more, and to add the % which is missing from the ps output. Then sort numerically according to the third field.

    Or with ps doing the sorting:

    ps --no-headers -o pid,user,%mem --sort %mem |
        awk -v "arg=$1" '$3 >= arg {print $0 "%"}'