2

Let's say I run the following commands:

sleep 500
/bin/sleep 500
sleep 30

What I'm interested is, how to count the number of instances of the sleep program, with certain arguments (in this case the only argument is 500).

So in the example above, if I count the number of instances of /bin/sleep 500, it should return 2.

I tried this: pgrep -xfc '/bin/sleep 500', but since it exactly matched the argument in the parenthesis, sleep 500 isn't counted.

  • Are you running a system with a /proc filesystem? That makes it easier to find the pathname of each process's executable. – Mark Plotnick May 25 '16 at 18:13
  • @MarkPlotnick Yes, I am – mythic May 25 '16 at 18:49
3

In your example you can go with:

pgrep -fc 'sleep 500'

It matches both /bin/sleep 500 and sleep 500.

Or if you want to be more precise:

pgrep -fc 'sleep 500$'
3

On GNU system:

$ ps --no-header -C sleep -o args | grep -Ec ' 500( |$)'
2
2

On systems that support a Linux-like /proc:

#!/bin/sh
if [ $# != 2 ]
then
    echo usage: "$0" pathname commandline_regexp
    exit 1
fi
cd /proc
for p in [0-9]*
do
    exe=$(readlink $p/exe 2>/dev/null)
    if [ "$exe" = "$1" ] &&
        cat $p/cmdline 2>/dev/null | tr '\0' ' ' | grep -q -- "$2"
    then
        echo match $p
    fi
done

example:

$ sleep 500&
[3] 18280
$ sleep 600&
[4] 18281
$ ./rpgrep /bin/sleep '.*sleep 500 $'
match 18280
$ ./rpgrep /bin/sleep '.*sleep.*00'
match 18280
match 18281

Notes:

  • the 2>/dev/null and the separate cat process are used to cope with the possibility that processes may disappear while the script is running.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.