Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created February 19, 2015 19:39
Show Gist options
  • Select an option

  • Save skarllot/89a02dd63aadce95ab8b to your computer and use it in GitHub Desktop.

Select an option

Save skarllot/89a02dd63aadce95ab8b to your computer and use it in GitHub Desktop.
Locking for Bash scripts
#!/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
@sinaowolabi

Copy link
Copy Markdown

Nice script!
But does it clear the lockfile once its stopped running?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment