Skip to content

Instantly share code, notes, and snippets.

@esoupy esoupy/LockFile.sh
Last active Dec 10, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jun 25, 2015

Versus the lockfile utility?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.