Search code examples
bashmemoryawkgrepps

Get memory percentage usage using pgrep and not ps


I have a bash scrip that is getting the memory percentage using the ps command as follows:

g_var_mem=$(ps -aux | grep myproc | grep -v grep | awk '{print $4}')

The output is 0.3 for my particular process.

When I use ShellCheck to check the script, I am gettin a SC2009 message stating "Consider using pgrep instead of grepping ps output.".

Is there anyway to use pgrep to get this memory percentage? Or another way that will get rid of this warning?


Solution

  • IMHO, you need not to use 2 times grep with awk, use single awk instead.

    ps -aux | awk '!/awk/ && /your_process_name/{print $4}'
    

    Explanation of above code:

    ps -aux | awk '                      ##Running ps -aux command and passing its output to awk program here.
    !/awk/ && /your_process_name/{       ##Checking condition if a line NOT having string awk AND check string(which is your process name) if both conditions are TRUE then do following.
      print $4                           ##Printing 4th field of the current line here.
    }'                                   ##Closing condition BLOCK here.