Check Running Processes

I want to check how many processes are running with same names and get their respective counts.

ps -ef|grep  -Eo 'process1|process2|process3| '|sort -u | awk '{print $2": "$1}'

Output would look like :

$ ps -ef|grep  -Eo 'process1|process2|process3| '|sort | uniq -c | awk '{print $2": "$1}'
: 108977
process1: 1
process2: 1
process3: 1

It should show 0 values against process1, process 2 and process 3 but it is calculating 1 process for grep command, how to ignore it and get 0.

Does your system have pgrep? If so, does it support the -c, --count option?
Try this:

#!/bin/bash
for process in "$@"
do
   printf "%s: %d\n" $process $(pgrep -c $process)
done

Andrew

1 Like

Unfortunately my system doesn't support pgrep. :confused:

Hi

Did you try | grep -v grep | ?

ps -ef|grep  -Eo 'process1|process2|process3| '|grep -v grep |sort | uniq -c | awk '{print $2": "$1}'
1 Like

How about

ps -e -o comm | grep  -Eo 'process1|process2|process3| '|sort | uniq -c

When using ps always use the -o option to specify exactly which fields you need rather than use a full listing and remove the ones you don't.

Andrew

1 Like

With the -E flag that you are already using, the search is for a regular expression. You can include an expression so that grep will not find itself like this:-

ps -ef | grep -E "Hell[o]"

The [o] matches the single character o which seems illogical until you recognise that the grep process will therefore not match, so it excludes itself.

You have several options separated with pipes so you pick the row if you match any of the items so you will need to do this to each part.

Two more thoughts:-

  • You have a search pattern of a space. Is that really what you want? I would expect much more output if that were true.
  • Your sort -u seems in the wrong place. Perhaps this might be better:-
    text ps -eo comm= | grep -Eo "whateve[r]|somethin[g]|els[e]" | sort | uniq -c
    I use -o comm= to strip out the headings.

    You do end up with the output the other way round. Is that a problem?

I hope that this helps,
Robin

3 Likes

Hey Radioactive,
Am sorry, it would give same result as before.

$ ps -ef|grep  -Eo 'process1|process2|process3| '|grep -v grep |sort | uniq -c | awk '{print $2": "$1}'
: 108766
process1: 1
process2: 1
process3: 1

---------- Post updated at 05:04 AM ---------- Previous update was at 05:02 AM ----------

Thanks Andrew, it was helpful to certain extent. When I run your command, it gives no output, But I was looking for a output like this :

process1: 0
process2: 0
process3: 0

If there are no instances of your required processes they won't be listed in ps and therefore won't be counted by uniq .
Perhaps something like this will help you:

for p in process1 process2 process3
do
   printf "%s: %d\n" "$p" $(ps -e -o comm= | grep -F -c "$p")
done 

Andrew

1 Like

How about

ps -e -o comm | grep -Eo "process(1|2|3)" | sort | uniq -c
1 Like