use flock(1) to serialize concurrent runs of the same script and prevent overlapping cron/systemd-timer executions
domain: man7.org · 5 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗
Steps
Wrap a script invocation in a lock using a dedicated lock file: `flock -n /var/lock/myjob.lock -c '/path/to/script.sh'`, where -n/--nonblock exits immediately if another instance already holds the lock.
To wait up to a bounded time instead of failing immediately, use -w/--timeout <seconds> (fractional seconds allowed) so a second invocation waits briefly for the first to finish.
Inside a shell script, acquire a lock on a file descriptor with `( flock -n 9 || exit 1; ...commands under lock... ) 9>/var/lock/myjob.lock` to keep locking self-contained.
Make a script self-locking on its own path with the boilerplate `[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :` at the top, so it always re-execs itself under its own lock.
Use -s/--shared for read-style locks that multiple concurrent readers can hold simultaneously, reserving the default exclusive lock for writer-style critical sections.
Known gotchas
flock locks are advisory and tied to the file descriptor/process holding them; a crashed process releases the lock automatically, but a process that forks and lets the child outlive the parent's fd can keep a lock alive longer than expected.
Locking on a plain file path means the lock file must exist and be a consistent path across all invocations; a typo or relative-path mismatch between two script copies means they never actually contend for the same lock.
-w 0 is documented as equivalent to --nonblock, which surprises people who set a timeout of 0 expecting an instant infinite-wait fallback rather than an immediate failure.
Give your agent this knowledge — and 15,500+ more routes
One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus:
claude mcp add --transport http waymark https://mcp.waymark.network/mcp
Need this verified for your stack — or a route we don't have yet?