Check number of running scripts using ps

2019-02-20 03:31发布

问题:

I'm writing a script (show_volume.sh) which may be called several times in short intervals. I need a way to determine whether there is more than just one running instance of this script. I figured I could use ps, so I wrote this function in Bash:

is_only_process(){
    PCOUNT=`ps -a | grep show_volume.sh | wc -l`
    echo $PCOUNT
    if (( PCOUNT==1 )); then
        return 1 
    fi  
    return 0
}

So I added these 2 lines

is_only_process
sleep 4

and started this script once, but the output of echo $PCOUNT does not make any sense to me. I always get the value 2, not 1, as expected. When I run this command

ps -a | grep show_volume.sh | wc -l

from another terminal while the script is running, I receive the value 1. It's pretty much the same when I run this script several times in a row, e.g. 10 times using a for loop. The script itself determines values which are too high while I receive correct values when using another terminal.

Now, why does this script determine these odd values?

回答1:

At the moment ps runs a process grep show_volume.sh is also running, so you always count the grep!

Simple solution, grep s[h]ow_volume.sh. The grep (not shell) will collapse the [h] to h and search for what you want, but your grep won't match itself because it will have [] in the parameter.

pgrep is also useful for this task and is smart enough to always exclude itself.



回答2:

Try to exclude grep as well, as your grep itself also contains show_volume.sh, an example

ps -a | grep show_volume.sh | grep -v grep | wc -l


回答3:

If you're running the script as different users then ps -a will only show instances for the current user and only those with an attached terminal. Use ps -ax or ps -e.

pgrep -c

will show a count without having to use wc.



回答4:

The solution provided by ajreal:

ps -a | grep show_volume.sh | grep -v grep | wc -l

should work. If it does not, please provide output of

ps -a | grep show_volume.sh | grep -v grep

here



标签: bash sh ps