Skip to content

Instantly share code, notes, and snippets.

@przemoc
Last active April 14, 2026 09:39
Show Gist options
  • Select an option

  • Save przemoc/571091 to your computer and use it in GitHub Desktop.

Select an option

Save przemoc/571091 to your computer and use it in GitHub Desktop.

Revisions

  1. przemoc revised this gist Feb 6, 2018. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions lockable_script_boilerplate.sh
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    #!/bin/bash
    # SPDX-License-Identifier: MIT

    ## Copyright (C) 2009 Przemyslaw Pawelczyk <przemoc@gmail.com>
    ##
  2. przemoc revised this gist Jan 10, 2017. 1 changed file with 5 additions and 3 deletions.
    8 changes: 5 additions & 3 deletions lockable_script_boilerplate.sh
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,9 @@
    #!/bin/bash

    ## Copyright (C) 2009 Przemyslaw Pawelczyk <przemoc@gmail.com>
    ## License: GNU General Public License v2, v3
    ## Copyright (C) 2009 Przemyslaw Pawelczyk <przemoc@gmail.com>
    ##
    ## This script is licensed under the terms of the MIT license.
    ## https://opensource.org/licenses/MIT
    #
    # Lockable script boilerplate

    @@ -30,4 +32,4 @@ unlock() { _lock u; } # drop a lock
    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.
    # the only script holding the lock or lock is not acquired at all.
  3. przemoc created this gist Sep 8, 2010.
    33 changes: 33 additions & 0 deletions lockable_script_boilerplate.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #!/bin/bash

    ## Copyright (C) 2009 Przemyslaw Pawelczyk <przemoc@gmail.com>
    ## License: GNU General Public License v2, v3
    #
    # Lockable script boilerplate

    ### 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.