Learn how to use the `flock` tool to serialize access to files and critical sections from shell scripts. 02.01.2026 | reading time: 2 min Concurrent scripts often race when they write the same file; `flock` is a small, reliable wrapper around POSIX file locks that lets a process take a shared or exclusive lock so access is serialized. Quick working demo ```sh cat > /tmp/worker.sh <<'EOF' #!/bin/sh for i in 1 2 3; do ( flock -x 200 echo "$(date '+%H:%M:%S') PID $$ - iteration $i" >> /tmp/out.log sleep 1 ) 200>/tmp/my.lock done EOF chmod +x /tmp/worker.sh /tmp/worker.sh & /tmp/worker.sh & sleep 5 printf "%s\n" "---- /tmp/out.log ----" cat /tmp/out.log ``` Options that matter `flock` supports exclusive locks with -x and shared locks with -s, a nonblocking mode -n, and a timeout -w; you can lock by passing a filename directly or by locking an open file descriptor which is handy inside scripts and functions. Important behavior to expect Locks taken with `flock` are advisory and cooperate only with other processes that use locking; they are released automatically on file close or when the process exits, so use a dedicated lock file such as under /var/lock and take care with backgrounding and exec to avoid accidental release. Real world uses Use `flock` to protect log rotations, cron jobs, package operations, backup scripts, and any section of a shell script that must run single threaded; wrap a critical command with -c or use the file-descriptor form to hold a lock across multiple commands. When `flock` is not enough `flock` is great for simple advisory locking but consider fcntl or application-level coordination for complex multi-threaded programs, and remember NFS can behave differently so test in your environment before deploying to distributed storage. Next steps Try adding traps to close descriptors on exit, create a small utility that centralizes locking logic, and inspect active locks with tools like `lsof` to learn more; deepen the skill set by studying GNOME util-linux source or lock primitives in C. Join Bits & Bytes Academy First class LINUX exam preparation. filesystem utilities scripting security