Follow-Up: Bash script locking with flock

After my post Easy bash script locking with mkdir I got a lot of feedback and I've learned a lot about locking (Credits to my co-worker @nine_ch).

One thing I've learned: Linux has flock. This is a kernel function which can be used with a tool called flock (yes, the same name as the kernel function). With this tool we can have an easy locking for bash scripts. Example:

# stop on errors
set -e
 
scriptname=$(basename $0)
pidfile="/var/run/${scriptname}"
 
# lock it
exec 200>$pidfile
flock -n 200 || exit 1
pid=$$
echo $pid 1>&200
 
## Your code:

This needs some explanation:

  • Line 8 opens a file handle with ID 200 on $pidfile
  • Line 9 uses flock to lock file handle with ID 200 with exclusive access.
    The parameter -n means  "Fail (with an exit code of 1) rather than wait if the lock cannot be immediately acquired".
    This is catched by the two pipes (or operation) and will exit if the lock fails, f.e. if the handle is already locked
  • Line 10 writes the PID to the file handle

Everything after Your code is only run if the file has the exclusive lock on the file handle 200. This ensures that it only runs once at a time.

An great article on this topic can be found here: using flock to protect critical sections in shell scripts

My conclusion is: I use flock, it's much easier and more robust than the mkdir approach. If you need to write cross platform bash scripts (Linux, BSD, ...) better don't rely on flock, it's only available on Linux in this form.

You've successfully subscribed to Tobias Brunner aka tobru
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.