Bash Script Single Instance: Run Once at a Time
In this article
- Why You Need a Single-Instance Lock
- How Lock Files Work
- Ensure the lock is removed when the script exits
- ... your script's actual work ...
- Why Use mkdir Instead of a Lock File?
- Handling Stale Locks
- Using flock for a Simpler Solution
- ... your script ...
- Choosing Between mkdir and flock
- Common Pitfalls and Misconceptions
- Frequently Asked Questions
Yes, you can limit a bash script to run only one instance at a time, and the standard method is to use a lock file with a check-and-create operation that is atomic. This prevents race conditions where two copies of the script start simultaneously and both pass the lock check.
Why You Need a Single-Instance Lock
When a script is run by cron, a webhook, or a user double-clicking an icon, nothing stops a second copy from starting before the first finishes. This can cause serious problems:
- Data corruption – two processes writing to the same file or database can interleave writes.
- Resource exhaustion – each instance consumes CPU and memory, and if the script is heavy, the system may slow down or run out of memory.
- Duplicate side effects – sending the same email twice, charging a customer twice, or starting two backups that overwrite each other.
- Deadlocks – if each instance waits for a resource the other holds, both hang forever.
Locking is a simple way to serialize execution: only one copy runs at a time, and others either wait or exit.
How Lock Files Work
The classic approach is to create a file (e.g., /tmp/myscript.lock) and check if it already exists. If it exists, another instance is running, so the script exits. If not, the script creates the file and removes it at the end.
The critical part is the atomic check-and-create. Two instances could both check the file, see it doesn't exist, and both create it. To avoid that, use mkdir (which is atomic) or a hard link, not a plain touch.
Here is a minimal, working example:
#!/bin/bash
LOCKDIR="/tmp/myscript.lock"
if ! mkdir "$LOCKDIR" 2>/dev/null; then
echo "Another instance is running." >&2
exit 1
fi
Ensure the lock is removed when the script exits
trap 'rmdir "$LOCKDIR"' EXIT
... your script's actual work ...
The mkdir command fails if the directory already exists, and that failure is the signal that another instance is running. The trap ensures the lock is removed even if the script is killed or errors out.
Why Use mkdir Instead of a Lock File?
Many tutorials show a lock file with if [ -e /tmp/lock ]; then exit; fi; touch /tmp/lock. That has a race condition: two processes can both see the file doesn't exist, and both create it. Using mkdir avoids that because the kernel guarantees only one process can create a directory.
Another advantage of mkdir is that it doesn't require external tools like flock or lockfile, which may not be installed on minimal systems. It is also easy to inspect: if the directory exists, you can put a PID file inside it to see which process holds the lock.
To store the PID, simply write it after creating the directory:
echo $$ > "$LOCKDIR/pid"
Then you can check the process with ps -p $(cat $LOCKDIR/pid) to see if it's still alive.
Handling Stale Locks
If the script crashes or is killed with kill -9, the trap won't run and the lock directory remains. The next run will think another instance is active and exit, even though no process is running. This is the most common problem with lock files.
There are several ways to handle stale locks:
- Manual cleanup – the user deletes the lock directory. Simple but requires human intervention.
- PID check – store the PID, and before failing, check if that PID is still running. If not, remove the lock and continue.
- Automatic expiry – record a timestamp and remove the lock if it's older than a certain age (e.g., 1 hour). This is useful for long-running scripts, but risky if a legitimate run takes longer than the expiry.
Here is an example with PID checking:
if ! mkdir "$LOCKDIR" 2>/dev/null; then
if [ -f "$LOCKDIR/pid" ]; then
old_pid=$(cat "$LOCKDIR/pid")
if ! kill -0 "$old_pid" 2>/dev/null; then
# Process not running, remove stale lock
rm -rf "$LOCKDIR"
# Try again
mkdir "$LOCKDIR" 2>/dev/null || { echo "Still locked"; exit 1; }
else
echo "Another instance is running (PID $old_pid)" >&2
exit 1
fi
else
echo "Lock exists but no PID file" >&2
exit 1
fi
fi
This is more robust but still has a tiny race: the PID could be reused by another process. For most purposes, that's acceptable.
Using flock for a Simpler Solution
If your system has flock (part of util-linux, present on most Linux distributions), it offers a cleaner way. You can lock a file descriptor, and the lock is automatically released when the process exits, even if it's killed.
The simplest form:
#!/bin/bash
exec 9>/tmp/myscript.lock
if ! flock -n 9; then
echo "Another instance is running." >&2
exit 1
fi
... your script ...
The -n flag means non-blocking: if the lock is held, the command fails immediately. Without -n, the script would wait until the lock is released, which is useful if you want to queue instances.
You can also use flock with a command:
flock /tmp/myscript.lock -c /path/to/your/script.sh
This is often used in cron entries to prevent overlapping runs.
Choosing Between mkdir and flock
Both methods are valid, but they have trade-offs:
- mkdir – more portable (works on any POSIX system, no extra tools), but you must handle stale locks manually.
- flock – simpler and more robust (no stale locks), but requires util-linux, which is standard on Linux but not on macOS or BSD by default.
- lockfile – from procmail, but rarely installed by default.
For a script that runs on a Linux server, flock is usually the best choice. For maximum portability, use mkdir with PID checking.
Common Pitfalls and Misconceptions
Misconception: A lock file prevents two instances if you check with -e. As explained, that check is not atomic. Always use mkdir or flock.
Pitfall: Forgetting to remove the lock on exit. Use trap to clean up, or flock which does it automatically.
Pitfall: Locking the wrong path. Use a path that is unique to the script, e.g., /tmp/myscript.lock or /var/run/myscript.pid. If two different scripts use the same lock, they will block each other.
Pitfall: Not considering the working directory. If you use a relative path for the lock, it depends on where the script is run from. Always use an absolute path.
Pitfall: Race in PID check. The PID could be reused. To be safer, you can check the process start time, but that's overkill for most scripts.
Frequently Asked Questions
Does flock work on macOS?
macOS does not include flock by default. You can install it via Homebrew (brew install util-linux), or use the mkdir approach instead. On Linux, flock is almost always available.
Can I make the script wait instead of exiting if another instance is running?
Yes. With flock, omit the -n flag and the script will wait until the lock is released. With mkdir, you would need a loop that retries, which is more complex and can waste CPU.
What if my script runs longer than the stale lock timeout?
If you use a timeout, make it longer than the maximum expected run time. A safer approach is to use PID checking instead of a timeout, because a legitimate long run won't be killed.
How do I test if the lock works?
Run the script in one terminal, then run it again in another. The second should exit with your error message. You can also add a sleep 30 inside the script to give yourself time to test.
Is it safe to use a lock file in /tmp?
Generally yes, but /tmp can be cleaned by the system, and on multi-user systems another user could create a file with the same name (a symlink attack). For security-sensitive scripts, use a directory like /var/run or a user-specific directory like ~/.cache.
Can I lock a script that runs as different users?
Yes, but the lock file must be accessible to all users. For example, /tmp/myscript.lock is world-writable, so any user can create it. However, this also means a malicious user could create the lock and prevent the script from running. For multi-user scenarios, consider using a system-wide lock like /var/run/myscript.pid with appropriate permissions.