Skip to content

Instantly share code, notes, and snippets.

@esoupy
Last active December 10, 2015 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save esoupy/4478169 to your computer and use it in GitHub Desktop.
Save esoupy/4478169 to your computer and use it in GitHub Desktop.
Bash LockFile function to prevent multiple executions of the same script. Remember to include 'LockFile remove' with any script exits to prevent lingering stale lock files.
#!/bin/bash
## LockFile function ##
# example:
# main() {
# LockFile create
# RunScriptStuff
# LockFile remove
# }
#Globals
Prog=$(basename $0)
Pid=$$
PidFile=/tmp/$Prog.pid
LockFile() {
## Manage LockFile ##
# Usage: LockFile [ create | remove | test ] #
_LockCmd=$1
rcode=0
case $_LockCmd in
test) [ -f $PidFile ] && _LockPid=$(cat $PidFile) && rcode=1
[ $_LockPid ] && [ -d /proc/$_LockPid ] && rcode=2
[ $rcode -eq 1 ] && echo "Stale Lockfile (pid:$_LockPid)"
[ $rcode -eq 2 ] && echo "Active Lockfile (pid:$_LockPid)"
return $rcode
;;
remove) [ -f $PidFile ] && rm -f $PidFile
;;
create) LockFile test
RetVal=$?
[ $RetVal -eq 2 ] && echo "Error: $Prog already running." && exit 1
if [ $RetVal -eq 1 ]; then
echo "Info: Removing stale lockfile."
LockFile remove
fi
touch $PidFile
echo $Pid > $PidFile
;;
*) echo "[Internal Error] $FUNCNAME: unknown argument '$_LockCmd'."
;;
esac
}
@opsroller
Copy link

Versus the lockfile utility?

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