bashconcurrencyflock

bash flock: exit if can't acquire lock


The following lock mechanism is used for preventing a cron job from running concurrently:

#!/bin/bash

echo "Before critical section"
(
    flock -e 200
    echo "In critical section"
    sleep 5
) 200>/tmp/blah.lockfile
echo "After critical section"

When running two instances together, the later waits until the first finishes, and then runs. This can cause backlogs of scripts waiting to run.

How do I alter this script so that if flock can't acquire the lock, it terminates the script? I've tried -n without success.


Solution

  • flock -n -e 200 || exit 1
    

    flock -n tells you it failed by returning a failure code (something other than zero). You could instead do set -e at the top of your script to make it exit when it sees any unchecked error.

    Depending on your application, you might want to exit 0 to indicate success when the lock can't be acquired.