The Analogy: The Single-Line Railway Token
Picture a stretch of railway where a single track carries trains in both directions between two stations. Only one train may be inside that section at a time; if two enter from opposite ends, they meet head-on. The signalman cannot manage this with a spoken promise or a note in a ledger, because a promise can be forgotten and a ledger can be misread. He needs a physical object that grants permission and that, by its very nature, cannot be in two places at once.
The railway's answer is the token instrument. At each end of the section sits an electrically interlocked machine holding a set of identical metal tokens, and the two machines are wired together so that only one token, from the whole pair of instruments, can be withdrawn at any moment. A driver may enter the section only if the signalman hands him the token; he carries it the length of the single line and surrenders it to the instrument at the far end, where it locks home and frees the interlock so the next token can be drawn. While a token is out, both machines refuse to release another. Permission is something you hold in your hand, and double-issue is physically impossible.
A script wants the same guarantee. A cron job, a nightly backup, a deploy -- you want exactly one copy running, and if two start at the same instant, exactly one must proceed and the other must stand down. The lock is the token. Acquiring it must be atomic, an operation the system performs indivisibly, so that of two racing copies precisely one succeeds. The humble mkdir is our interlock: the kernel guarantees that creating a given directory succeeds for exactly one caller and fails for every other, which is all the mutual exclusion a lock needs.
Now suppose the train breaks down inside the section and the crew, following the rules, keep the token with them. Both instruments still show a token withdrawn; no other train may enter; the line is blocked even though the rails are now clear. Only a supervisor with a special release key can override the interlock. A plain lock file catches the same disease. A script killed with kill -9, or stopped by a power cut, leaves its lock in place with no living owner. Every later run finds the lock, concludes another copy is active, and refuses -- forever, until a human clears it by hand. The rest of this lesson is about choosing a lock that either cannot be orphaned or can prove whether its owner is still alive.
Syntax or Core Structure
The cheapest correct lock is a directory. mkdir either creates the directory and succeeds, or finds it already there and fails -- and it does so atomically, in one indivisible step, which is exactly what a lock needs:
lock=/tmp/demo.lock.d
if mkdir "$lock" 2>/dev/null; then
echo "acquired"
else
echo "busy"
fi
if mkdir "$lock" 2>/dev/null; then
echo "acquired"
else
echo "busy"
fi
rmdir "$lock"
Output:
acquired
busy
The first mkdir wins and prints acquired; the second finds the directory already present, fails, and prints busy. Two copies racing to create the same directory get the same clean split -- one and only one sees acquired. The 2>/dev/null hides mkdir's own "File exists" complaint so that only our own message reaches the screen.
Technical Depth: Choosing a Lock That Heals
Four ways to hold a lock
Not every lock is equal. The four common mechanisms differ on the two properties that matter under stress -- whether the create is atomic, and whether the lock frees itself when the holder dies unexpectedly:
| Mechanism | Atomic create | Frees itself on crash | Needs external tool |
|---|---|---|---|
mkdir dir | yes | no | no |
set -o noclobber then > file | yes | no | no |
flock fd | yes | yes, kernel drops it | yes, util-linux |
PID file plus kill -0 | no, two steps | recoverable | no |
Both mkdir and noclobber are portable and atomic, but neither ever self-heals: if the holder dies without cleaning up, the token is orphaned. flock is the only option the kernel releases automatically when the holding process exits for any reason, including kill -9, because the lock lives on the open file description rather than on disk. Its price is a dependency on util-linux, which is absent on some minimal images and non-Linux systems.
noclobber: an atomic create with a plain file
With the noclobber shell option set, the > redirection refuses to overwrite an existing file and fails instead, giving you an atomic create-or-fail on an ordinary file whose contents can name the owner:
f=/tmp/demo.lock
( set -o noclobber; echo "$$" > "$f" ) && echo "created" || echo "exists"
( set -o noclobber; echo "$$" > "$f" ) 2>/dev/null && echo "created" || echo "exists"
rm -f "$f"
Output:
created
exists
The first subshell creates the file and prints created; the second is refused by noclobber and prints exists. Writing $$ (the shell's own process id) into the file leaves a breadcrumb: a later run can read it and ask whether that owner is still alive.
flock ties the lock to a descriptor
flock takes a file descriptor rather than a path, and it holds the lock for exactly as long as that descriptor stays open. The idiom opens a descriptor onto a lock file and asks for a non-blocking lock:
exec 9>/tmp/service.lock
if flock -n 9; then
echo "got the lock; working"
else
echo "another copy holds it; exiting"
exit 1
fi
Output:
got the lock; working
Because the lock rides on descriptor 9, you never rmdir or rm anything: when the script exits -- normally, by error, or by kill -9 -- the kernel closes the descriptor and releases the lock. That is the self-healing property mkdir cannot offer. The -n makes a second copy fail at once instead of blocking; drop it and the second copy waits its turn. (flock ships with util-linux and is absent on some non-Linux shells, so the output above is its documented behaviour on a Linux host.)
Telling a live lock from a corpse
For locks that do not self-heal, record the owner's PID and test it with kill -0, which sends no signal but succeeds only when the process exists and you are allowed to signal it:
echo 999999 > /tmp/demo.pid
pid=$(cat /tmp/demo.pid)
if kill -0 "$pid" 2>/dev/null; then
echo "holder $pid alive"
else
echo "holder dead (stale lock)"
fi
rm -f /tmp/demo.pid
Output:
holder dead (stale lock)
PID 999999 is not running, so kill -0 fails and we judge the lock stale and safe to break; had it printed alive we would back off. The catch: PIDs are recycled, so a stale PID can coincidentally match an unrelated live process, and then kill -0 lies and you refuse to run for nothing. That reuse hazard is why flock, which needs no PID bookkeeping at all, is preferred wherever it exists.
Why the trap must cover the error path
A release that only runs on the last line is worthless the moment the script fails early. Registering the release as an EXIT trap makes bash run it however the script ends -- including when set -e aborts on a failed command:
set -euo pipefail
cleanup() { echo "released"; }
trap cleanup EXIT
echo "before"
false
echo "after"
Output:
before
released
The false fails, set -e aborts the script before echo "after" can run, yet the EXIT trap still fires and prints released. That is why the guard registers rmdir as an EXIT trap rather than calling it on the final line: an error, a return, or a plain exit all still hand the token back. The one gap the trap cannot cover remains kill -9, which is exactly where flock earns its keep -- and the reason production locks lean on the kernel rather than on disciplined cleanup alone.
Real World Example: A Single-Instance Cron Guard
Cron has no memory of its own past. If a job is scheduled every minute but occasionally takes ninety seconds, cron will happily start a second copy on top of the first, and now two backups are trampling the same files. The guard below gives the job a token: it takes an atomic mkdir lock, and an EXIT trap makes sure a normal or errored run always hands the token back.
#!/usr/bin/env bash
# single.sh -- run the body only if no other copy holds the lock
set -euo pipefail
LOCK_DIR="${LOCK_DIR:-/tmp/single.lock.d}"
if ! mkdir "$LOCK_DIR" 2>/dev/null; then
echo "already running (lock: $LOCK_DIR); exiting"
exit 0
fi
trap 'rmdir "$LOCK_DIR"' EXIT
echo "acquired lock; working"
echo "work done; releasing"
Run it on a clean system and it takes the lock, does its work, and the EXIT trap removes the lock directory on the way out:
bash single.sh
Output:
acquired lock; working
work done; releasing
Start it and, while it is still working, launch a second copy. The second mkdir fails because the directory already exists, so the second copy announces itself and exits 0 -- a clean, quiet no-op that cron will not send mail about:
bash single.sh
Output:
already running (lock: /tmp/single.lock.d); exiting
The trap is the entire safety net, and it has the hole the railway analogy warned about. trap ... EXIT fires on a normal exit and on ordinary signals, but not on kill -9 or a power loss: the process simply vanishes without running the trap, the lock directory survives, and every future run reads "already running" although nothing is running -- the orphaned token, blocking the line until a human removes it by hand. The second flaw compounds the first: the lock records nothing about its owner. Because it stores no PID, a stale lock is indistinguishable from a live one, so the script cannot safely break a lock it suspects is dead without risking the murder of a healthy sibling. A production version would write $$ into the lock and use kill -0 to decide whether an existing lock is broken and stealable, or it would abandon mkdir for flock and let the kernel handle release correctly for free. As written, single.sh is safe against races but not against crashes -- which is precisely the trade-off mkdir makes.
Common Mistakes
- Testing then creating in two steps.
[ -e lock ] || touch lockis not atomic: two copies can both pass the existence test before either creates the file, and both proceed. Use one atomic operation --mkdirorset -o noclobber-- that creates and checks together.
- Releasing only on the last line. If you
rmdirthe lock only at the end of the script, any earlyexitorset -efailure leaves it held forever. Install the release in atrap ... EXITso it runs on every path out.
- Trusting
trap ... EXITto survivekill -9. A hard kill and a power loss skip every trap. A lock that only a trap releases will be orphaned bykill -9; design for that case withflockor a PID check rather than assuming the trap always fires.
- Locking on a path that varies per run. If the lock name contains
$$or a timestamp, every copy computes a different name and the lock excludes no one. The lock path must be stable and identical across all copies of the job.
- Breaking someone else's lock blindly.
rmdirorrma lock you did not create and you may free one a live sibling still holds. Only break a lock after proving its owner is dead, or use a mechanism the kernel releases for you.
- Putting the lock on a network filesystem. The atomicity guarantees of
mkdirandflockweaken or disappear on NFS and many networked mounts. Keep locks on a local filesystem such as/tmp,/run, or/var/lock.
- Forgetting that
flockblocks by default. Without-n,flockwaits indefinitely, so a stuck holder makes every new copy hang instead of exiting. Choose-nto fail fast or-w SECONDSfor a bounded wait, on purpose.
- Assuming a PID file proves liveness. PIDs are recycled, so a stale PID can match an unrelated running process and
kill -0will call a dead lock alive. Pair the PID with a second signal such as start time or process name when the stakes are high.
- Leaking the lock descriptor into children. A background child inherits
flock's descriptor 9 and keeps the lock open after the parent exits, so it is not released when you expect. Close it in children withexec 9>&-or open the lock close-on-exec.
Best Practices
- Prefer
flockon any Linux host. It is atomic, needs no cleanup, and the kernel releases it on every form of death includingkill -9-- the one property a hand-rolled lock cannot match.
- Make acquisition a single atomic step. Use
mkdirorset -o noclobberso create-and-test happen together, never a separate existence test followed by a create.
- Release with a trap, not a final line. Install
trap 'rmdir "$LOCK_DIR"' EXITor theflockequivalent so the lock frees on normal exit, onset -efailures, and on ordinary signals.
- Store the owner's PID inside the lock. Writing
$$into the lock lets a later run usekill -0to tell a live holder from a stale token and recover safely.
- Keep locks on a local filesystem. Put them under
/tmp,/run, or/var/lock, never on NFS, so the atomicity guarantees actually hold.
- Choose the wait policy deliberately. Use
flock -nto fail fast in cron jobs andflock -w SECONDSwhen a short wait is acceptable; never let a job block forever by default.
- Give each job its own lock name. Derive the lock path from the job's identity, stable across runs, so unrelated jobs never exclude each other and the same job always collides with itself.
- Make "already running" a clean exit. Return
0with a quiet message when the lock is held, so cron does not treat a normal skip as a failure and flood you with mail.
Practice Exercises
- Atomic guard from scratch. Write a script that takes a lock with
mkdir, printsworking, sleeps two seconds, and releases the lock in an EXIT trap. Start two copies half a second apart and confirm that exactly one printsworkingwhile the other reports the lock busy.
- Stale-lock recovery. Extend the guard to store
$$in a file inside the lock directory. On finding an existing lock, read that PID and usekill -0to decide: break the lock and proceed if the holder is dead, exit if it is alive. Test both branches with a real and a fake PID.
- Port it to flock. On a Linux host, rewrite the guard with
exec 9>andflock -n 9, deleting all manual cleanup. Kill the holder withkill -9and show that a fresh copy still acquires the lock, proving the kernel released it.
- Bounded wait. Change the
flockversion to wait up to five seconds withflock -w 5before giving up. Start a second copy while the first holds the lock and measure that it either acquires the lock within five seconds or exits non-zero when the first does not finish in time.