Using Lock Files to Prevent Duplicate Runs
Many automation scripts must never run twice at the same time. A backup that runs while the previous backup is still writing can produce a broken archive; two copies of an import script can process the same file twice; a deployment started twice can leave a server half-updated. Duplicate runs happen more often than expected: cron starts a job every five minutes whether or not the last run has finished, an administrator starts a script by hand while the scheduled run is busy, or a slow network makes one run take much longer than usual.
The usual protection is a lock: before doing its work, the script tries to take a lock that only one process can hold at a time. If it gets the lock, it works and releases the lock when it ends; if another process already holds it, the script either exits at once or waits. On Linux, the lock is normally tied to a file, called a lock file, so that separate processes can agree on it.
This lesson explains why the obvious "check whether a file exists" approach does not work, then covers the three techniques that do: mkdir, the noclobber option, and the flock command, which is the right tool on Linux. It ends with a queue-processing script that uses flock correctly.
Why "Check, Then Create" Is Not a Lock
A first idea is to test whether a lock file exists, exit if it does, and create it otherwise:
#!/bin/bash
lock=/srv/t171/naive.lock
if [ -e "$lock" ]; then
echo "$$: already running, exiting"
exit 1
fi
sleep 0.2 # stands for the tiny gap between the check and the creation
touch "$lock"
echo "$$: got the lock, working"
sleep 1
rm -f "$lock"
Two copies started at the same moment (./naive.sh & ./naive.sh & wait) both get through:
617: got the lock, working
616: got the lock, working
The problem is that checking and creating are two separate steps. Both processes check, both see no file, and both create it. The sleep 0.2 makes the gap large enough to see every time, but without it the gap still exists; it is just short, so the failure happens rarely, which is worse, because it is hard to reproduce. This kind of bug is called a race condition (or a TOCTOU bug, for "time of check to time of use").
A working lock needs a single operation that both tests and takes the lock, and that the operating system guarantees can succeed for only one process. Such an operation is called atomic.
Locking with mkdir
Creating a directory is atomic: if two processes run mkdir on the same name at the same moment, the kernel lets exactly one succeed, and the other gets "File exists". That makes mkdir a portable lock that works in any POSIX shell:
#!/bin/bash
lock=/srv/t171/job.lock.d
if ! mkdir "$lock" 2>/dev/null; then
echo "$$: already running, exiting"
exit 1
fi
trap 'rmdir "$lock"' EXIT
echo "$$: got the lock, working"
sleep 1
630: got the lock, working
631: already running, exiting
The trap ... EXIT (lesson 123) removes the directory when the script ends, whether it ends normally, with an error, or through exit. After both runs, the lock directory is gone.
The weakness is that the lock lasts as long as the directory exists, not as long as the process lives. If the script is killed with kill -9, or the machine loses power, the trap never runs and the directory stays. Every later run then refuses to start:
649: got the lock, working
killed, status 137
653: already running, exiting
status 1
This leftover is called a stale lock. Someone has to notice and delete it by hand, and until they do, the job silently stops running.
Locking with noclobber
The noclobber option (set -o noclobber or set -C, lesson 148) makes the > redirection refuse to overwrite an existing file. Bash implements this by opening the file with the O_EXCL flag, so the existence test and the creation happen in one atomic system call. That makes > with noclobber a lock, and it has an advantage over mkdir: the lock file can contain something, such as the process ID of the holder.
#!/bin/bash
lock=/srv/t171/job.pid
if ! ( set -o noclobber; echo "$$" > "$lock" ) 2>/dev/null; then
echo "$$: locked by PID $(< "$lock"), exiting"
exit 1
fi
trap 'rm -f -- "$lock"' EXIT
echo "$$: got the lock, working"
sleep 1
660: got the lock, working
661: locked by PID 660, exiting
The option is set inside a subshell ( ... ), so it does not stay on for the rest of the script. The 2>/dev/null hides the message Bash prints when the file exists:
/bin/bash: line 37: job.pid: cannot overwrite existing file
Detecting stale PID locks
Because the file holds a process ID, the script can check whether that process still exists with kill -0 (lesson 140), and remove the lock if it does not:
#!/bin/bash
lock=/srv/t171/job.pid
if ! ( set -o noclobber; echo "$$" > "$lock" ) 2>/dev/null; then
old=$(< "$lock")
if [[ $old =~ ^[0-9]+$ ]] && kill -0 "$old" 2>/dev/null; then
echo "$$: PID $old is still running, exiting"
exit 1
fi
echo "$$: removing stale lock left by PID $old"
rm -f -- "$lock"
( set -o noclobber; echo "$$" > "$lock" ) 2>/dev/null || { echo "$$: lost the race, exiting"; exit 1; }
fi
trap 'rm -f -- "$lock"' EXIT
echo "$$: got the lock, working"
sleep 1
The first run is killed with kill -9; the next run finds the stale lock and takes over, and a third run started during the second one is turned away:
696: got the lock, working
lock still contains: 696
701: removing stale lock left by PID 696
701: got the lock, working
708: PID 701 is still running, exiting
This works most of the time, but it has gaps that are hard to close in shell code:
- PID reuse. Process IDs are recycled. After a crash and a reboot, the old number may belong to a completely unrelated process, and
kill -0says it is alive, so the lock is never cleared. - Races in the cleanup. If two new runs find the same stale lock at the same moment, one can delete the lock that the other has just created. The second
noclobberattempt above narrows the window but does not close it completely. - Permissions.
kill -0fails for a living process owned by another user (lesson 140), which looks like a dead process.
Stale locks exist because the lock is a file whose life is separate from the process. The flock command removes that separation.
Locking with flock
flock (part of util-linux, installed on practically every Linux system) uses the kernel's file-locking system call flock(2). The key difference from the previous techniques: the lock is not "the file exists", it is a lock that the kernel attaches to an open file. When the process that opened the file exits, for any reason including kill -9 or a crash, the kernel closes its files and releases the lock automatically. Stale locks cannot exist; the lock file can be left on disk forever, and its presence means nothing.
The standard pattern opens the lock file on a spare file descriptor with exec (lesson 115), then asks flock to lock that descriptor:
#!/bin/bash
exec 9> /srv/t171/job.lock
if ! flock -n 9; then
echo "$$: another run holds the lock, exiting"
exit 1
fi
echo "$$: got the lock, working"
sleep "${1:-1}"
echo "$$: done"
exec 9> /srv/t171/job.lockopens (and creates if needed) the file for writing on descriptor 9, which stays open for the whole script. The number is arbitrary; 9 is conventional because scripts rarely use descriptors that high.flock -n 9tries to take an exclusive lock on descriptor 9.-n(non-blocking) means: if another process holds the lock, fail at once with status 1 instead of waiting.- There is no
trapand norm: the lock is released when descriptor 9 is closed, which happens automatically when the script ends.
Running two copies:
738: got the lock, working
742: another run holds the lock, exiting
second status 1
738: done
What "open file" means for child processes
A test with kill -9 gave a surprising result at first. The first run (./flock1.sh 30, which runs sleep 30) was killed, and yet the next run still found the lock taken:
744: got the lock, working
killed 137
748: another run holds the lock, exiting
status 1
The reason is that child processes inherit open file descriptors. The sleep 30 started by the script received its own copy of descriptor 9, pointing to the same open file. Killing the script did not kill sleep, and as long as any process holds that open file, the lock stays. The process list showed it:
pgrep -a sleep
ls -l /proc/747/fd | grep job.lock
747 sleep 30
l-wx------ 1 root root 64 Nov 25 18:09 9 -> /srv/t171/job.lock
After sleep ended, the next run got the lock. Usually this inheritance is exactly right: if the script's work is still running in a child process, the lock should still be held. It becomes a problem when a script starts something that is meant to outlive it, such as a background server or a daemon, because that process keeps the lock forever. The fix is to close descriptor 9 for that one command with 9>&-:
sleep "${1:-1}" 9>&- # the child does not get the lock descriptor
With this change, killing the script releases the lock at once, even though the orphaned sleep is still running:
823: got the lock, working
killed 137
827: got the lock, working
827: done
status 0
Waiting for the lock
Without -n, flock waits until the lock is free. -w SECONDS waits at most that long:
#!/bin/bash
exec 9> /srv/t171/job.lock
SECONDS=0
if ! flock -w "$1" 9; then
echo "$$: gave up after $SECONDS s"
exit 1
fi
echo "$$: got the lock after $SECONDS s"
With a 3-second job holding the lock, a run that waits 1 second gives up, and a run that waits up to 10 seconds gets the lock when the job finishes:
837: got the lock, working
841: gave up after 1 s
status 1
837: done
843: got the lock after 2 s
Which behavior to use depends on the job. For a periodic job such as a cron task, skipping (-n) is usually right: the next scheduled run will do the work. For a command that must happen, such as a deployment requested by a person, waiting (with a limit) is better.
The command form
flock can also run a command while holding the lock, which is convenient in crontab lines and for wrapping scripts that were not written with locking in mind:
flock -n /srv/t171/job.lock sleep 2 &
flock -n /srv/t171/job.lock echo hi; echo "busy status $?"
flock -n -E 75 /srv/t171/job.lock echo hi; echo "busy -E status $?"
flock -n -E 0 /srv/t171/job.lock echo hi; echo "busy -E 0 status $?"
busy status 1
busy -E status 75
busy -E 0 status 0
In this form, flock opens the file itself (creating it if needed), takes the lock, runs the command, and exits with the command's status:
flock -n /srv/t171/job.lock sh -c 'echo working; exit 3'; echo "free status $?"
working
free status 3
That creates an ambiguity: status 1 could mean "the lock was busy" or "the command failed with 1". -E CODE sets the status for the busy case, so the two can be told apart; 75 (EX_TEMPFAIL, "try again later") is a common choice, and -E 0 makes a skipped run count as success, which keeps cron from mailing about it. If the lock file cannot be opened at all, for example because its folder does not exist, flock reports it and exits with 66:
flock: cannot open lock file /srv/t171/newdir/x.lock: No such file or directory
missing folder 66
A crontab line that keeps a job from overlapping with itself looks like this:
*/5 * * * * flock -n -E 0 /run/lock/sync-reports.lock /usr/local/bin/sync-reports.sh
Locking a block of code
The descriptor can be opened for a single compound command instead of the whole script, with the redirection after the closing brace. The lock then covers just that block. This is useful when several processes update the same file. The following script starts 50 background functions, each of which adds 1 to a number stored in a file, first without a lock and then with one:
#!/bin/bash
counter=/srv/t171/counter
add_one_unlocked() {
n=$(< "$counter")
echo $(( n + 1 )) > "$counter"
}
add_one_locked() {
{
flock 9
n=$(< "$counter")
echo $(( n + 1 )) > "$counter"
} 9> "$counter.lock"
}
for mode in unlocked locked; do
echo 0 > "$counter"
for i in {1..50}; do
"add_one_$mode" &
done
wait
echo "$mode: $(< "$counter")"
done
Three runs gave the same result each time:
unlocked: 1
locked: 50
Without the lock, the read and the write of different processes interleave. The > redirection empties the file before the new number is written, so processes that read the file at that moment see an empty value, and $(( + 1 )) gives 1. With flock 9 (waiting, no -n), each update runs alone, and all 50 are counted.
Shared and exclusive locks
flock locks are exclusive by default (-x). A shared lock (-s) can be held by any number of processes at once, but not while someone holds an exclusive lock. This is the classic readers-and-writer arrangement: scripts that only read a data file take shared locks and run in parallel, and a script that rewrites the file takes an exclusive lock and waits until all readers are finished:
reader() { ( flock -s 9; echo "reader $1 in"; sleep 1; echo "reader $1 out" ) 9> /srv/t171/data.lock; }
writer() { ( flock -x 9; echo "writer in"; sleep 0.5; echo "writer out" ) 9> /srv/t171/data.lock; }
reader 1 & reader 2 & sleep 0.2; writer & wait
reader 1 in
reader 2 in
reader 1 out
reader 2 out
writer in
writer out
Both readers were inside at the same time; the writer, started while they were reading, waited until both had left.
Releasing early
A lock can be released before the script ends with flock -u 9. The descriptor stays open, but other processes can now take the lock:
( exec 9> /srv/t171/u.lock; flock 9; echo "phase 1 locked"; flock -u 9; echo "released, still open"; sleep 1 ) &
sleep 0.3; flock -n /srv/t171/u.lock echo "other got it during phase 2"
phase 1 locked
released, still open
other got it during phase 2
Closing the descriptor (exec 9>&-) releases it as well.
Locking the script file itself
The flock manual page suggests a one-line header that makes a script lock itself, using its own file as the lock file, so that no separate lock file is needed:
#!/bin/bash
[ "${FLOCKER:-}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
echo "$$: running with args: $*"
sleep 1
On the first pass, FLOCKER is not set, so the script replaces itself (exec) with flock -en "$0" "$0" "$@": flock locks the script file and runs the script again with the same arguments, this time with FLOCKER set, so the line does nothing and the script continues. -e is the same as -x (exclusive). A second copy started while the first is running fails at the flock step with status 1:
1146: running with args: one
second status 1
The trick is compact, but it locks per script file, not per job: two runs of the same script on different data cannot run in parallel, and the script must be readable by the user who runs it.
Rules for Lock Files
Never delete a flock lock file
With mkdir and noclobber, removing the lock is how it is released. With flock, deleting the file is a bug. The lock belongs to the file's inode (the file itself), not to its name. If a finished run deletes the file, a process that was already waiting holds a lock on the deleted file, and the next process to start creates a new file with a new inode, which is not locked by anyone. The following script waits for the lock (no -n) and, wrongly, deletes the file when it is finished. Three copies, A, B and C, were started half a second and two seconds apart:
#!/bin/bash
lock=/srv/t171/rm.lock
exec 9> "$lock"
flock 9 # wait until the lock is free
echo "$1: got the lock (inode $(stat -c %i -L /proc/$$/fd/9))"
sleep 2 9>&-
echo "$1: done"
rm -f -- "$lock" # WRONG: deleting the lock file when finished
A: got the lock (inode 804114)
A: done
B: got the lock (inode 804114)
C: got the lock (inode 804047)
B: done
C: done
B had opened the file while A was running and got the lock when A finished, but A then deleted the name. C created a new file (a different inode) and locked it immediately, so B and C ran at the same time: exactly what the lock was meant to prevent. Leave flock lock files in place; an empty file costs nothing.
Do not truncate the holder's information
Writing the holder's PID into a flock lock file is useful for diagnostics, but exec 9> "$lock" opens the file with >, which empties it. Every run that fails to get the lock therefore erases what the holder wrote. Two scripts that differ only in the opening line show the difference:
#!/bin/bash
lock=/srv/t171/info.lock
exec 9> "$lock" # info-bad.sh: empties the file on every open
if ! flock -n 9; then
echo "$$: busy, holder: '$(< "$lock")'"
exit 1
fi
echo "pid $$" >&9
sleep 1 9>&-
#!/bin/bash
lock=/srv/t171/info.lock
exec 9>> "$lock" # info-good.sh: opens for appending, no truncation
if ! flock -n 9; then
echo "$$: busy, holder: '$(< "$lock")'"
exit 1
fi
truncate -s 0 -- "$lock" # only the lock holder empties the file
echo "pid $$" >&9
sleep 1 9>&-
Starting each one and then two more copies during its run:
1857: busy, holder: ''
1859: busy, holder: ''
1866: busy, holder: 'pid 1861'
1868: busy, holder: 'pid 1861'
With >>, only the process that holds the lock empties the file, and because the descriptor was opened in append mode, its write goes to the start of the now-empty file.
Where to put lock files
/run/lock(also reachable as/var/lockon most systems) is meant for lock files. On most distributions it is a memory-based file system that is emptied at boot, and it is writable by all users with the sticky bit set (drwxrwxrwt).- For a job that belongs to an application, a lock file inside the application's own folder, owned by the user who runs the job, is often simpler and safer.
- Avoid predictable names in shared, world-writable folders such as
/tmpfor jobs run as root (lesson 154). Another user can create the name first, as a symbolic link to an important file. On the test machine, the usernobodycreated/tmp/job171.lockas a link to a root-owned file, and root'sexec 9> /tmp/job171.lockfollowed the link and emptied that file. Most distributions enable the kernel settingfs.protected_symlinks, which blocks following such links in sticky world-writable folders, but the test machine had it switched off, so a script should not depend on it./run/lockhas the same sticky-bit permissions, so root jobs are best given a lock file in a folder only root can write to, such as/run/myjob/or the application's folder. flocklocks are reliable on local file systems. On network file systems such as NFS, locking depends on the server and client configuration; keep lock files on local storage.
A Complete Example: A Queue Processor That Runs Once at a Time
process-queue.sh processes order files that other systems drop into a queue folder. Each file is counted, recorded in a report and moved to done (or to failed if it is empty). It is meant to run from cron every few minutes, so it must never run twice: two copies would read the same file, both add it to the report, and one of the mv commands would fail.
#!/usr/bin/env bash
#
# process-queue.sh - process the files waiting in a queue folder, one run at a time
#
# Usage: process-queue.sh [-w SECONDS] QUEUE_DIR
# -w SECONDS if another run is active, wait up to SECONDS for it (default: 0,
# which means skip this run at once)
#
# Every *.csv file in QUEUE_DIR/incoming is counted, a line is added to
# QUEUE_DIR/report.txt, and the file is moved to QUEUE_DIR/done (or to
# QUEUE_DIR/failed when it is empty). PQ_DELAY=SECONDS slows each file down,
# which is useful for testing the lock.
#
# Exit status: 0 all files done, or run skipped because another run is active
# 1 at least one file failed
# 2 usage or setup error
# 75 gave up waiting for the lock (only with -w)
set -uo pipefail
wait_secs=0
usage() { echo "usage: ${0##*/} [-w SECONDS] QUEUE_DIR" >&2; exit 2; }
log() { printf '%(%H:%M:%S)T [%s] %s\n' -1 "$$" "$*"; }
while getopts ':w:' opt; do
case $opt in
w) [[ $OPTARG =~ ^[0-9]+$ ]] || usage; wait_secs=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
queue=$1
[[ -d $queue/incoming ]] || { echo "${0##*/}: no incoming folder in '$queue'" >&2; exit 2; }
mkdir -p -- "$queue/done" "$queue/failed" || exit 2
# --- the lock -------------------------------------------------------------
# Open with >> so that a run that fails to get the lock does not empty the
# file and erase the holder's details.
lock=$queue/.lock
exec 9>> "$lock" || { echo "${0##*/}: cannot open lock file '$lock'" >&2; exit 2; }
if ! flock -w "$wait_secs" 9; then
holder=$(< "$lock")
if (( wait_secs == 0 )); then
log "another run is active (${holder:-holder unknown}), skipping"
exit 0
fi
log "gave up after ${wait_secs}s waiting for ${holder:-another run}"
exit 75
fi
# We hold the lock: record who we are, for anyone who finds it busy.
truncate -s 0 -- "$lock"
printf 'pid %s since %(%H:%M:%S)T\n' "$$" -1 >&9
# The lock is released automatically when this script and every process that
# inherited descriptor 9 have exited, so there is nothing to clean up.
# --- the work ---------------------------------------------------------------
shopt -s nullglob
files=( "$queue"/incoming/*.csv )
if (( ${#files[@]} == 0 )); then
log "nothing to do"
exit 0
fi
failed=0
for file in "${files[@]}"; do
name=${file##*/}
lines=$(wc -l < "$file")
sleep "${PQ_DELAY:-0}" 9>&- # child processes need not inherit the lock
if (( lines == 0 )); then
mv -- "$file" "$queue/failed/"
log "$name: empty, moved to failed"
failed=1
continue
fi
printf '%s %s %d orders\n' "$(date +%F)" "$name" "$lines" >> "$queue/report.txt"
mv -- "$file" "$queue/done/"
log "$name: $lines orders"
done
exit "$failed"
How It Works
- The lock is the first thing the script does after checking its arguments. It is taken before the script even lists the files, so two runs can never see the same list.
exec 9>> "$lock"opens the lock file in append mode, so runs that fail to get the lock do not erase the holder's details.flock -w "$wait_secs" 9waits up to the given number of seconds. With the default of 0, it behaves like-nand returns at once.- A busy lock is not an error when skipping. A periodic job that finds the previous run still active exits with 0 and a log line, so cron does not send a failure mail every few minutes. When the caller explicitly asked to wait (
-w) and the wait ran out, the script exits with 75, the conventional "temporary failure, try again" status. - The holder records itself in the lock file with its PID and start time, after emptying it with
truncate, so a skipped run can say who it is waiting for. - No cleanup code. There is no
trapand norm; the kernel releases the lock when the script ends, however it ends. sleep ... 9>&-stands for long-running work. Closing the descriptor for that child means that if the script is killed, an orphaned child does not keep the lock.nullgloband an array (lessons 82 and 149) handle file names with spaces and an empty queue correctly.
Running the Complete Example
A test queue was set up in /srv/queue/incoming with four files: orders-0901.csv (3 lines), orders 0902.csv (2 lines, with a space in the name), orders-0903.csv (empty) and orders-0904.csv (4 lines). A test script started one slow run (PQ_DELAY=1) in the background and then, while it worked, three more runs: one with the default (skip at once), one waiting up to 1 second, and one waiting up to 10 seconds:
Q=/srv/queue
PQ_DELAY=1 /srv/t171/bin/process-queue.sh "$Q" &
sleep 0.5
/srv/t171/bin/process-queue.sh "$Q"; echo "[second run: status $?]"
/srv/t171/bin/process-queue.sh -w 1 "$Q"; echo "[third run, -w 1: status $?]"
/srv/t171/bin/process-queue.sh -w 10 "$Q"; echo "[fourth run, -w 10: status $?]"
wait $!; echo "[first run: status $?]"
18:10:57 [1705] another run is active (pid 1697 since 18:10:56), skipping
[second run: status 0]
18:10:57 [1697] orders 0902.csv: 2 orders
18:10:58 [1708] gave up after 1s waiting for pid 1697 since 18:10:56
[third run, -w 1: status 75]
18:10:58 [1697] orders-0901.csv: 3 orders
18:10:59 [1697] orders-0903.csv: empty, moved to failed
18:11:00 [1697] orders-0904.csv: 4 orders
18:11:00 [1716] nothing to do
[fourth run, -w 10: status 0]
[first run: status 1]
The second run saw the lock busy and skipped with status 0. The third waited one second and gave up with 75. The fourth waited until the first run finished at 18:11:00, then got the lock and found the queue empty. The first run exited with 1 because one file was empty. Every file was handled exactly once:
$ cat /srv/queue/report.txt
2026-11-25 orders 0902.csv 2 orders
2026-11-25 orders-0901.csv 3 orders
2026-11-25 orders-0904.csv 4 orders
$ ls /srv/queue/done /srv/queue/failed
/srv/queue/done:
orders 0902.csv
orders-0901.csv
orders-0904.csv
/srv/queue/failed:
orders-0903.csv
$ cat /srv/queue/.lock
pid 1716 since 18:11:00
The lock file still exists and still names the last holder; that is harmless, because only the kernel's lock counts, not the file's content or existence.
To check recovery from a crash, two new files were queued and a slow run (PQ_DELAY=5) was killed with kill -9 half a second after it started, in the middle of its first file. The next run started immediately afterwards:
[first run killed: status 137]
18:11:05 [1768] orders-0905.csv: 1 orders
18:11:05 [1768] orders-0906.csv: 2 orders
[next run: status 0]
There was no stale lock to remove by hand. The killed run's sleep child was still running as an orphan, but because it had been started with 9>&-, it did not hold the lock. The file the killed run had been working on had not been moved yet, so the next run processed it.
Invalid use is reported with status 2:
$ process-queue.sh
usage: process-queue.sh [-w SECONDS] QUEUE_DIR
$ process-queue.sh -w abc /srv/queue
usage: process-queue.sh [-w SECONDS] QUEUE_DIR
$ process-queue.sh /srv/nowhere
process-queue.sh: no incoming folder in '/srv/nowhere'
To run it every five minutes, the crontab line needs no extra locking, because the script locks itself:
*/5 * * * * /usr/local/bin/process-queue.sh /srv/queue >> /var/log/process-queue.log 2>&1