Repository navigation
Expand file tree
/
Copy pathsingleton
More file actions
executable file
·83 lines (74 loc) · 2.36 KB
/
Copy pathsingleton
File metadata and controls
executable file
·83 lines (74 loc) · 2.36 KB
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
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env bash
#
# Requirement:
# - flock
#
# Author: James Cherti
# URL: https://github.com/jamescherti/bash-stdops
#
# Description:
# ------------
# This script functions as a mutual exclusion wrapper. It prevents concurrent
# executions of the same operation by using a dedicated lockfile.
#
# Usage Example:
# singleton /var/run/backup.lock /usr/local/bin/backup.sh --verbose
#
# The above command prevents concurrent executions of the
# /usr/local/bin/backup.sh script. Running the command a second time while the
# first instance is active results in an error message and a non-zero exit code,
# which prevents multiple executions:
# singleton /var/run/backup.lock /usr/local/bin/backup.sh --verbose
#
# Here is the error message caused by the second execution:
# Error: Another instance of '/usr/local/bin/backup.sh' is running.
#
# License:
# --------
# Copyright (C) 2012-2026 James Cherti
#
# Distributed under terms of the GNU General Public License version 3.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
set -euf -o pipefail
main() {
if [[ $# -lt 2 ]]; then
printf "Usage: %s <lockfile> <command> [args...]\n" "$0" >&2
exit 1
fi
local lockfile="$1"
shift
local -a cmd=("$@")
local command_name="${cmd[0]}"
# Ensure secure permissions for the lockfile creation
local old_umask
old_umask=$(umask)
umask 077
# Open file descriptor for the lockfile
local lockfd
exec {lockfd}>"$lockfile"
umask "$old_umask"
# Attempt to acquire an exclusive, non-blocking lock
if ! flock -x -n "$lockfd"; then
printf "Error: Another instance of '%s' is running.\n" "$command_name" >&2
exit 1
fi
# Release the lock when the shell exits.
# shellcheck disable=SC2064
trap "exec $lockfd>&-" EXIT
# Execute the provided command
"${cmd[@]}"
}
main "$@"