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:
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:
To check if myCommand is executed, the simplest is to list processes, grep lines with myCommand.sh. 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 myCommand.sh) or simpling displaying it (e.g. cat myCommand.sh). It is up to you to set the restriction.