Self-locking script

For anything cron or a login hook might start twice (straight from the flock man page): the script re-executes itself under flock, using its own file as the lock. The second invocation exits instead of racing the first.

[ "${FLOCKER-}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :

-e exclusive, -n fail instead of queue (drop -n to wait). The || : keeps the guard line’s exit status at 0; without it, a script ending on this line reports failure.

Caveats: flock is util-linux (absent on stock macOS), and advisory locks are unreliable on NFS/AFS, so lock a file in /tmp instead of "$0" there. Contention exits silently; log before || : if you need to know.

esc