Preventing Multiple Instances of a Script From Running Using flock

Linux command line programSometimes you want to limit a script to just one instance. Say the script accesses a resource that you don’t want to be shared. So how do you prevent multiple instances of a single script from running?

You can do this with the flock command. So for example:

flock /var/run/run_lock -c /something/to/script.sh

flock works by setting a lock on the run_lock file for the duration of the script’s execution.

By default flock waits for the lock to be available. But you can also set it to exit immediately if it can’t get a lock using the -n switch:

flock -n /var/run/run_lock -c /something/to/script.sh

So if the script is running while you run flock a second time the second flock command will fail immediately.

flock is useful in cron jobs where you want to run a command periodically but not if a previous instance is already active:

* * * * * flock -n /var/run/runlock -c /my/prettty/script.php

In the above instance script.php will be executed once every minute if a previous instance is not running. So if script.php takes longer than a minute to run you won’t have multiple instances of it launched.

flock can also be used on directories and within shell scripts. See man flock for the full manual.

One thought on “Preventing Multiple Instances of a Script From Running Using flock

Leave a Reply

Your email address will not be published. Required fields are marked *