Created
February 19, 2015 19:39
-
-
Save skarllot/89a02dd63aadce95ab8b to your computer and use it in GitHub Desktop.
Locking for Bash scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # See: http://www.kfirlavi.com/blog/2012/11/06/elegant-locking-of-bash-program/ | |
| readonly PROGNAME=$(basename "$0") | |
| readonly LOCKFILE_DIR=/tmp | |
| readonly LOCK_FD=200 | |
| lock() { | |
| local prefix=$1 | |
| local fd=${2:-$LOCK_FD} | |
| local lock_file=$LOCKFILE_DIR/$prefix.lock | |
| # create lock file | |
| eval "exec $fd>$lock_file" | |
| # acquier the lock | |
| flock -n $fd \ | |
| && return 0 \ | |
| || return 1 | |
| } | |
| eexit() { | |
| local error_str="$@" | |
| echo $error_str | |
| exit 1 | |
| } | |
| main() { | |
| lock $PROGNAME \ | |
| || eexit "Only one instance of $PROGNAME can run at one time." | |
| do_A | |
| do_B | |
| } | |
| main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice script!
But does it clear the lockfile once its stopped running?