forked from noelmartinon/debian-server-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install-cron.sh
executable file
·90 lines (73 loc) · 2.23 KB
/
install-cron.sh
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
84
85
86
87
88
89
90
#!/bin/bash
#
# Install cron jobs from the script header.
#
# VERSION :0.2.4
# DATE :2016-02-13
# AUTHOR :Viktor Szépe <viktor@szepe.net>
# LICENSE :The MIT License (MIT)
# URL :https://github.com/szepeviktor/debian-server-tools
# BASH-VERSION :4.2+
# Usage
#
# Add a line to your script's header: "# CRON-HOURLY :/usr/local/bin/example.sh"
# Cron.d syntax: "# CRON.D :09,39 * * * * root /usr/local/bin/example.sh"
# See: crontab(5)
Error()
{
local RET="$1"
shift
echo -e "$*" 1>&2
exit "$RET"
}
Valid_cron_interval()
{
local QUESTION="$1"
for VALID in cron.daily cron.hourly cron.monthly cron.weekly; do
if [ "$QUESTION" == "$VALID" ]; then
return 0
fi
done
return 1
}
SCRIPT="$1"
if [[ $EUID -ne 0 ]]; then
Error 1 "Only root is allowed to install cron jobs."
fi
if [ ! -f "$SCRIPT" ]; then
Error 2 "Please specify an existing script."
fi
# @TODO Rewrite: loop through valid crons
# and $(head -n 30 "$SCRIPT"|grep -i "^# ${CRON}")"|cut -d':' -f2 >> "$CRON_FILE")
CRON_JOBS="$(head -n 30 "$SCRIPT" | grep -i '^# CRON')"
if [ -z "$CRON_JOBS" ]; then
Error 3 "No cron job in script."
fi
declare -i JOB_ID="0"
declare -i JOB_ID_D="0"
while read -r JOB; do
CRON_INTERVAL="$(echo "$JOB" | cut -d " " -f 2 | tr '[:upper:]' '[:lower:]')"
CRON_INTERVAL="${CRON_INTERVAL/-/.}"
if Valid_cron_interval "$CRON_INTERVAL"; then
CRON_FILE="/etc/${CRON_INTERVAL}/$(basename "${SCRIPT%.*}")$(( ++JOB_ID ))"
# Create simple shell script
{
echo "#!/bin/bash"
echo "$JOB" | cut -d ":" -f 2-
} > "$CRON_FILE"
chmod 755 "$CRON_FILE"
echo "[cron] ${SCRIPT} -> ${CRON_FILE}"
elif [ "$CRON_INTERVAL" == cron.d ]; then
CRON_FILE="/etc/cron.d/$(basename "${SCRIPT%.*}")"
# Initialize cron.d file
if [ $(( ++JOB_ID_D )) -eq 1 ]; then
rm -f "$CRON_FILE"
touch "$CRON_FILE"
fi
# Append job to cron.d file
echo "${JOB}" | cut -d ":" -f 2- >> "$CRON_FILE"
echo "[cron] ${SCRIPT} -> ${CRON_FILE}"
else
Error 10 "Invalid cron interval in script header: (${CRON_INTERVAL})"
fi
done <<< "$CRON_JOBS"