Skip to content
Kelly (KT) Thompson edited this page Dec 9, 2019 · 1 revision

Introduction

I use this command to prevent multiple instances of shell scripts (usually started by cron) from stomping on each other. There is a ton of examples on the internet to look at. For example, https://linuxaria.com/howto/linux-shell-introduction-to-flock.

Use in scripts started by cron

For my setup, a typical script will have logic like this

lockfile=/var/tmp/$USER/sync_repository_$target.lock
[ "${FLOCKER}" != "${lockfile}" ] && exec env FLOCKER="${lockfile}" flock -en "${lockfile}" "${0}" "$@" || :

If the script is called while the lockfile exists, then execution is paused until the lock file is removed.