Is a script running?

On a *nix system, it is often desirable to ensure that a script is running as a singleton (I borrow the C++ term). For example, if a process is scheduled to run every 10min and for some reason last for 11, for sure you don’t want it to be run again.

There are some tricks, like locking a socket and checking its status before running, but I guess it impose quite a lot of programmation, maybe a bit difficult for a shell script. A simpler way is to trigger the script from another one (let’s call it singleton) that is charged to check if the script (cunningly named myCommand) is already running or not, like:

singleton myCommand

What should do singleton? Well, there are two cases: either myCommand is an executable directly run by the system or it is a script. If it is an executable, then pidof let’s you check if it is running:

pidof -s -x myComnand

Now, if myCommand is a script, starting with a shabang (#!/bin/bash or #!/bin/env python, etc) pidof won’t find anything since the program actually running is bash or python and myCommand is only a parameter. Check it with ps -eaf | grep myCommand and you’ll see:

/bin/bash myPath/

To check if myCommand is executed, the simplest is to list processes, grep lines with Don’t forget to add an inverse grep on grep itself (grep -v grep):

result=$(ps -eaf | grep -v grep | grep myCommand)

if [ -z “$result” ]; then



Of course, you can be less restrictive when selecting processes from ps. In this case, singleton won’t run anything if you are editing the script (example vi or simpling displaying it (e.g. cat It is up to you to set the restriction.


0 Responses to “Is a script running?”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

August 2009
« Apr   Sep »

%d bloggers like this: