Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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.
                The right way to do this to find proc but not awk '/proc/ is to write the script as ps -aux | awk '/pro[c]/{print $4}.
– Ed Morton
                Dec 7, 2018 at 18:08
                This would be good, but instead of having "0.3" type of value, it does not get rid of the space in front, " 0.3".
– Kris
                Dec 7, 2018 at 16:47
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.