How Can I Tell If My Bash Script Is Already Running? – Part 2

Master LockIn my first posting on this topic I outlined a manual method by which you could code Bash scripts to check to see whether or not an instance of the script was already running. This is very useful in scripts that might cause adverse affects if more than one instance runs at the same time. I have since started using a built-in Linux command to accomplish this in a much easier fashion. The command I’ve started using is called flock. This simple command creates and maintains file locks from scripts and/or the command line. So now I can do something like this:

So what does this do? Well, the -x option tells flock to create an exclusive lock. On what? On the lock file you specify: /var/lock/myscript. The -n option tells flock to exit if it cannot not obtain a lock, instead of waiting to acquire one. The last argument is the script or command that you want to run while holding the file lock. Pretty easy, right?

Finally, you may not actually have the flock command in your Linux distribution. One of my Linux servers did not have it while another did. The CentOS server that I run has it listed under the util-linux package. Of course the server that did not have the flock binary had the flock function call in a C header file, so if I were motivated enough I imagine I could right a flock program for that server (or compile one from source obtained from elsewhere on the internet).