#10 Locking Files

Any script that reads or appends to a shared data file, such as a log file, needs a reliable way to lock the file so that other instantiations of the script don't step on the updates. The idea is that the existence of a separate lock file serves as a semaphore, an indicator that a different file is busy and cannot be used. The requesting script waits and tries again, hoping that the file will be freed up relatively promptly, denoted by having its lock file removed.

Lock files are tricky to work with, though, because many seemingly foolproof solutions fail to work properly. For example, the following is a typical approach to solving this problem:

while [ -f $lockfile ] ; do
  sleep 1
done
touch $lockfile

Seems like it would ...

Get Wicked Cool Shell Scripts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.