Skip to content

Instantly share code, notes, and snippets.

@forestbaker
Last active September 29, 2015 17:35
Show Gist options
  • Save forestbaker/f36f28deaffa9951421b to your computer and use it in GitHub Desktop.
Save forestbaker/f36f28deaffa9951421b to your computer and use it in GitHub Desktop.
use flock to create an exclusive file lock like a pinch on the neck from mr. spock
http://www.kfirlavi.com/blog/2012/11/06/elegant-locking-of-bash-program/
Simple
#########################################
#!/bin/bash
# exit if flock fails.
set -e
# Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds
( flock -n 200 || exit 1 ) 200>/var/lock/.myscript.exclusivelock
#########################################
ADVANCED
#########################################
#!/bin/bash
readonly PROGNAME="$(basename "$0")"
readonly LOCKFILE_DIR='/tmp'
readonly LOCK_FD='200'
# exec attempts to secure a file descriptor
#
Lock_Flock_FD() {
local prefix="${1:+spockflocklock}"
local fd="${2:-$LOCK_FD}"
local lock_file="$LOCKFILE_DIR/${prefix}.lock"
eval 'exec "$fd">"$lock_file"'
[[ 1 -eq $? ]] \
&& echo "error : unable to acquire file descriptor $fd " && return 1
flock -n "$fd" \
&& return 0 \
|| return 1
}
# echo parameter as error message and exit - use " " or ' '
Err_Exit() {
local error_str="$@"
echo "error : $error_str : " >&
exit 1
}
main() {
lock $PROGNAME \
|| Err_Exit "one $PROGNAME at a time"
do_A
do_B
}
main
@forestbaker
Copy link
Author

I think i improved on the original a little

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