How does `flock` prevent concurrent runs of a script?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
flock takes an advisory kernel lock on a file. The lock is tied to the open file descriptor, so it is released automatically when the process exits, even on kill -9, unlike PID files.
exec 9>/run/lock/backup.lock
flock -n 9 || { echo "backup already running" >&2; exit 0; }
# ... rest of the script holds the lock until exit
# or wrap a whole command, e.g. in cron:
flock -n /run/lock/backup.lock /opt/opskit/bin/opskit-backup
-n fails immediately; -w 30 waits up to 30 seconds; without either it blocks.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner