Blah Blah Blah

bash script to check if a process instance is running

Posted in linux, technology by Pavan on July 9, 2008

#!/bin/bash
if [ $# -ne 2 ]
then
echo "$0 process_name instances_count"
exit 1
fi

function count_match {
echo Count Match #Your code goes here
}

function count_mismatch {
echo Count Mismatch #Your code goes here
}

process=$1
exp_count=$2

run_count=`ps eax | grep ${process} | grep -v grep | wc -l`

if [ ${exp_count} -eq ${run_count} ]
then
count_match
else
count_mismatch
fi

Please note “grep -v grep” is not be required for cygwin, but even if you retain it, it doesn’t alter the behavior.

7 Responses

Subscribe to comments with RSS.

  1. Vinod said, on July 9, 2008 at 10:55 am

    did you test this script ?
    you have to use
    ps eax | grep ${process} | grep -v grep | wc -l
    if you dont want to count the grep command!

  2. Pavan said, on July 9, 2008 at 6:11 pm

    @Vinod
    Thanks for the correction. I had tested this script under Cygwin and it worked just fine. However I incorporated the correction suggested by you and it should work consistently across *NIX.

  3. Pernod said, on July 23, 2008 at 3:49 pm

    You may want to correct the shebang as well – remove the blank like in
    #!/bin/bash

  4. Pavan said, on July 23, 2008 at 4:25 pm

    @Pernod,
    Thanks for pointing out, I updated my post.
    For those who are curious about ’shebang’, visit http://en.wikipedia.org/wiki/Shebang_(Unix)

  5. VowFoeloferop said, on August 3, 2008 at 8:30 am

    I agreed with you

  6. Pavan said, on August 14, 2008 at 3:40 am

    pgrep utility can also be used to achieve the above mentioned task;
    pgrep examines the active processes on the system and reports the process IDs of the processes.

    eg.
    run_count=`pgrep ${process} | wc -l`
    OR more succinctly
    run_count=`pgrep ${process} -c`

  7. Menda said, on December 19, 2008 at 11:51 pm

    This one is the best:

    if [ "$(pidof processname)" ] ; then
    echo ‘Process is running…’
    fi


Leave a Reply