There is a command called flock
that you can use from bash. It works like this
flock [options] file|directory --command command
(see the manpage for other syntaxes). It will create a lock file (or folder) and then execute the command if it was able to acquire the lock on the file. You can test it like this (start the two commands in parallel):
$ flock --verbose .lock sleep 10 && echo X > output
$ flock --verbose .lock sleep 10 && echo Y > output
these will create a .lock
file and write to output
as soon as they can acquire the lock. You can check the lock with cat /proc/locks
or lslocks
.
There is a gotcha however. These are all "advisory" locks, which means all your scripts must use flock or check the lock file otherwise. If another process decides to write without checking the lock, it will not have to wait for anybody and it will not be blocked.