Create a gist now

Instantly share code, notes, and snippets.

Lockable script
## Copyright (C) 2009 Przemyslaw Pawelczyk <>
## This script is licensed under the terms of the MIT license.
# Lockable script boilerplate
### HEADER ###
LOCKFILE="/var/lock/`basename $0`"
_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; }
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
# 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.
blezek commented Sep 24, 2012

Outstandingly useful script. Thanks!


ditto @dblezek


I don't know much about bash scripting, i have simple questions:

  1. my script should go at the end, after exlock_now || exit 1?
  2. do I have to call _no_more_locking explicitly at the end?
przemoc commented Dec 19, 2013


  1. Yes.
  2. No, _no_more_locking is called automatically when script ends.

Sorry for late reply, but unfortunately gists lack any notification system...

xHN35RQ commented Aug 15, 2015

Super helpful, thanks for this boilerplate. 🍹


@Przemoc really useful snippet! But have you thought about getting it on the MIT license?

The GPL v2 prevents me form using it, as I would basically have to publish the script somewhere and that would be quite useless given that the script will have probably 2 more lines :)

Let me know what you think.

przemoc commented Dec 13, 2015

There won't be a problem. I'll improve this boilerplate a bit by incorporating some of my comments you can find in and relicense it to MIT License (which I'm already using in my more recent creations). For the time being please use simply relicensed version I've sent to your github e-mail.

TUNER88 commented Dec 14, 2016

@przemoc any news about the improved version?

reesd commented Jan 10, 2017

Yes, would really like the MIT licensed version. "derivative work" can be a tricky with bash scripts.

As suggestion would be making it a sourceable library also that could be used across multiple scripts. Perhaps taking the lockname rather than using basename.

przemoc commented Jan 10, 2017

commit 6571db3000d4060e4168c3406f370a02a32b5045 (2017-01-10 23:54:05 +0100): Relicense to MIT.

I wanted to do it long time ago, along with some updates, but it's so
low on my todo list, that only comment on stackoverflow changed it:

because I pasted the code there.

Sorry, no code updates yet.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment