flock(1)
Manage file locks from the shell, allowing exclusive or shared access to files or file descriptors.
Synopsis
flock [OPTION]... FILE COMMAND [ARG]...
flock [OPTION]... FDDescription
flock acquires a lock on a file or file descriptor, holding it for the duration of a command or script. Locks can be exclusive (write) or shared (read), and the command will wait until the lock is available unless you use nonblocking mode. This is useful for coordinating access to resources across multiple processes, particularly in shell scripts and cron jobs.
When used with a FILE argument, flock opens or creates the file and acquires the lock on it. When used with a file descriptor (FD), it operates on an already-open descriptor. The lock is automatically released when the command exits or the file descriptor is closed.
Common options
| Flag | What it does |
|---|---|
-s, --shared | Acquire a shared lock (read lock) instead of exclusive; multiple processes can hold shared locks simultaneously |
-x, --exclusive | Acquire an exclusive lock (write lock); default behavior, prevents other locks on the file |
-n, --nonblock | Fail immediately if lock cannot be acquired instead of waiting; exit with code 1 |
-w, --wait SECONDS | Wait up to SECONDS for the lock; exit with code 1 if timeout expires |
-u, --unlock | Remove an existing lock; useful when lock file is passed as FD argument |
-c, --close | Close the file descriptor before executing the command; lock is retained |
-e, --exclusive | Explicitly set exclusive lock mode (same as -x) |
Examples
Acquire exclusive lock on /tmp/mylock.lock, run backup.sh, then release; prevents concurrent backups
flock /tmp/mylock.lock -c 'backup.sh'Try to acquire lock without waiting; if busy, skip sendmail queue processing to avoid conflicts
flock -n /var/lock/mail.lock sendmail -qUse shared lock for read-only operation; multiple reads can happen concurrently
flock -s /tmp/data.lock grep 'pattern' /tmp/data.txtWait maximum 30 seconds for lock; exit with status 1 if timeout occurs
flock -w 30 /tmp/resource.lock command-with-timeoutOpen file descriptor 3, lock it exclusively, then run critical section; lock persists for the shell session
exec 3> /tmp/script.lock && flock -x 3 && critical_section.shUnlock and release the lock held on file descriptor 4
flock -u 4Redirect to file descriptor 200, acquire exclusive lock, execute database write, then unlock
{ flock -x 200; database-write; } 200>/tmp/db.lock