How do you implement file locking in shell scripts?
Answer
File locking prevents multiple instances of a script from running simultaneously. The most robust method is flock: exec 9>/var/lock/myscript.lock; flock -n 9 || { echo "Already running"; exit 1; }. The lock is automatically released when the script exits (even on crash) because the FD is closed. Alternative — lockfile with PID: create a file containing the PID; check if PID is still running on startup; clean up on exit via trap. Use mkdir as an atomic lock: mkdir /tmp/mylock 2>/dev/null || { echo "Locked"; exit 1; } — mkdir is atomic on most filesystems. For distributed locking across servers, use Redis or a database. Always pair locks with trap ... EXIT for cleanup.
Previous
What is the difference between bash and POSIX sh scripting?
Next
How do you use associative arrays in bash?