Search code examples
bashgrepwc

Line count with top command


I need to find the number of processes that are running with a command name that matches a specific pattern. And I need to check for the number of processes on regular intervals.

I am grepping the output of the top command with the command pattern and attempting to find the number of processes every time.

The following will (for example) grep the all the processes that matches the command pattern and print it out dynamically.

top -bcd 1 | grep worker | grep apache

Now instead of the list, I just need the count of processes to print out dynamically. I tried the following that wont work for me.

top -bcd 1 | grep worker | grep apache | wc -l

and

top -bcd 1 | grep worker | grep -c apache

If there is a completely different and better way to do it, please let me know that as well.


Solution

  • In terms of the original problem in your question, i.e. checking the number of processes with a name matching a given pattern, I would suggest using pgrep with watch:

    watch pgrep apache
    

    You should be able to output this directly to a log file using a standard redirection > out. If that doesn't work, you could always roll your own loop to do something similar:

    while true; do
        pgrep apache
        sleep 2
    done > out