2

I would like to synchronize two Bash scripts via a file lock. How to do this? Zsh has zsystem flock call, but is there a more "shellish" method that's also available to Bash?

marked as duplicate by roaima, Thomas Dickey, GAD3R, slm bash Sep 10 '16 at 13:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

Apart from locking the file itself, you could create a file used as a lock (a lockfile). There are a bunch of utilities for this, e.g. procmail has lockfile, and in Debian, the liblockfile-bin package has dotlockfile. Procmail should be common enough to be available on most systems.

But basically it comes down to something like:

tempfile=$(mktemp ./lock.XXXX)
lockfile=./lockfile
if ln $tempfile $lockfile ; then
    echo got it
    # do something
    rm $lockfile # after you're done
else 
    echo did not succeed
fi
rm $tempfile

ln will not clobber the target if it already exists, unlike something like echo > file, instead you get an error you can check.

NOTE: if you want to do locks over NFS, use some tool made for that purpose. The semantics of concurrent access to files over NFS are... interesting to say the least.

Not the answer you're looking for? Browse other questions tagged or ask your own question.