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:
This needs some explanation:
- Line 8 opens a file handle with ID 200 on
- Line 9 uses
flockto lock file handle with ID 200 with exclusive access. The parameter
-nmeans “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
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.