Fork me on GitHub

Project Notes

#060 File Locks

How to implement simple resource semaphores with file locks.


For when we want to ensure that only one instance of a shell script can be run at the same time.

Operating system locks/semaphores can be used to traffic-light an operation. From a scripting environment, a utility must be used to get a lock - for example flock or man lockfile.

flock / lockfile

The flock utility should be available by default in most Linux distros. It used to be in MacOS also, but not since at least Yosemite. On MacOS, lockfile should be available though. The test script will look for either.


The script demonstrates locking with either flock parsing an invented syntax from an environment variable.

$ ./ & ./
[27428] Locked
[27428] Doing something interesting here... Mon Oct  9 23:13:27 SGT 2017
[27428] Loaded
[27427] Locked
[27427] Doing something interesting here... Mon Oct  9 23:13:35 SGT 2017
[27427] Loaded

Credits and References

About LCK#16 Bash
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.