-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbashlock
72 lines (65 loc) · 1.9 KB
/
bashlock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/bin/bash -eu
# vim: ts=4 sw=4 ai et
#
# Lockfile managing code.
bashlock() {
# Author: Sean Reifschneider <[email protected]>
# Date: Thu Sep 10, 2020
# License: 2-Clause BSD
# Code/Bugs: https://github.com/realgo/bashlock
#
# This is a function that implements a lockfile and exclusive access via
# that file. It's a bash function that manages the lockfile via a trap
# and is meant to easily be pulled into code to prevent multiple instances
# from running at once.
#
# Getting Started
# ---------------
#
# Copy the "bashlock" function into your code and then call it with a
# lockfile name, exit on failure:
#
# bashlock /var/run/lock/${0##*/}.pid || exit 1
# [Remainder of script code here]
# or:
#
# BASHLOCKFILE=/var/run/lock/${0##*/}.pid
# bashlock || exit 1
#
# Done!
#
# Exit Codes
# ----------
#
# The following exit codes are used:
#
# * 0: Lock successfully obtained
#
# * 1: Lock is held by another process
#
# * 2: Usage error
#
# * 3: Failed to write temporary lockfile
[ "$#" -eq 1 ] && BASHLOCKFILE="$1"
if [ -z "$BASHLOCKFILE" ]; then
echo 'usage: bashlock [LOCKFILENAME]' 1>&2
echo ' BASHLOCKFILE environment variable may be used' 1>&2
return 2
fi
echo "$$" >"$BASHLOCKFILE.$$" || return 3
if ! ln "$BASHLOCKFILE.$$" "$BASHLOCKFILE" 2>/dev/null; then
PID=$(head -1 "$BASHLOCKFILE")
if [ -z "$PID" ]; then
rm -f "$BASHLOCKFILE"
else
kill -0 "$PID" 2>/dev/null || rm -f "$BASHLOCKFILE"
fi
if ! ln "$BASHLOCKFILE.$$" "$BASHLOCKFILE" 2>/dev/null; then
rm -f "$BASHLOCKFILE.$$"
return 1
fi
fi
rm -f "$BASHLOCKFILE.$$"
trap 'rm -f "$BASHLOCKFILE"' EXIT
return 0
}