Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sergeifilippov/216e3cc21dd87cac03bf07fd71be70c6 to your computer and use it in GitHub Desktop.
Save sergeifilippov/216e3cc21dd87cac03bf07fd71be70c6 to your computer and use it in GitHub Desktop.
Lockable script
#!/bin/bash
## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
##
## This script is licensed under the terms of the MIT license.
## https://opensource.org/licenses/MIT
#
# Lockable script boilerplate
# If using on macOS, try https://github.com/discoteq/flock
### HEADER ###
LOCKFILE="/var/lock/`basename $0`"
LOCKFD=99
# PRIVATE
_lock() { flock -$1 $LOCKFD; }
_no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking() { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }
# ON START
_prepare_locking
# PUBLIC
exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail
exlock() { _lock x; } # obtain an exclusive lock
shlock() { _lock s; } # obtain a shared lock
unlock() { _lock u; } # drop a lock
### BEGIN OF SCRIPT ###
# Simplest example is avoiding running multiple instances of script.
exlock_now || exit 1
# Remember! Lock file is removed when one of the scripts exits and it is
# the only script holding the lock or lock is not acquired at all.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment