{ Limezest πŸ‹ }

Using `flock` for File Locking in Shell Scripts

Jun 10, 2025
2 minutes
shell tips

Today I learned about using flock to manage file access in shell scripts, ensuring that only one process can write to a file at any given time.
This is especially helpful when multiple processes might attempt to write to the same file concurrently, which can cause data corruption or loss.

flock uses file locks to control access. While this isn’t the most robust solution, it’s effective for simple scenarios and much easier to implement than a database or more complex locking systems.

Here’s an example of how to use flock to safely write to a file:

flock -x "$file".lock -c "echo \"$pnbr,$pid,$org\" >> $file"
Shell
#        ^^^^^^^^^^^^  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#    Lock file name    |   '-c' runs the command while the
#                      |   lock is held
Shell

While this approach may slow down your script if many processes are writing simultaneously, it guarantees that only one process writes at a time, preventing data issues. The slowdown is typically just a few milliseconds, so it’s suitable for most use cases.