A typical approach to avoid two instances of the same script running simultaneously looks like this:
[ -f '.lock' ] && exit 1 touch .lock # do something rm .lock
Is there a better way to lock on files from a shell-script, avoiding a race condition? Must directories be used instead?
Yes, there is indeed a race condition in the sample script. You can use bash’s
noclobberoption in order to get a failure in case of a race, when a different script sneaks in between the-ftest and thetouch.The following is a sample code-snippet (inspired by this article) that illustrates the mechanism: