Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps