-
Notifications
You must be signed in to change notification settings - Fork 15
/
run-if-today
executable file
·94 lines (81 loc) · 1.8 KB
/
run-if-today
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
91
92
93
94
#!/usr/bin/env bash
# run-if-today
# Run a cron task the first, nth or last weekday of the month.
#
# Homepage:
# https://github.com/xr09/cron-last-sunday
#
# Released under the MIT license.
# Examples:
#
# 1st Monday --> run-if-today 1 "Mon"
# 2nd Friday --> run-if-today 2 "Fri"
# last Sunday --> run-if-today [l|L] "Sun"
# Date ranges:
#
# Week Dates
# 1 1-7
# 2 8-14
# 3 15-21
# 4 22-28
# 5 29-lastday (you probably need [L]ast week instead)
# L (lastday-6)-lastday
ARRAY=( $(LC_TIME=en_US.UTF-8 date "+%Y %m %d %a") )
YEAR=${ARRAY[0]}
MONTH=${ARRAY[1]}
TODAY=${ARRAY[2]}
WEEK_DAY=${ARRAY[3]}
# If the day is provided but it is not that day of the week, don run all the checks
if [ ! -z "$2" ] && [ $WEEK_DAY != ${2:0:3} ]
then
exit 1
fi
# Ok, it's that day, let's run some fancy code.
# Which week in the month are we dealing with?
case "${1:0:1}" in
[1-5])
# Plain old nth day code.
MIN_DAY=$[ 1 + $[ 7 * $[ ${1:0:1} - 1 ] ] ]
MAX_DAY=$[ $MIN_DAY + 7 ]
if [ $TODAY -ge $MIN_DAY ] && [ $TODAY -lt $MAX_DAY ]
then
# Green light
exit 0
fi
;;
"l" | "L")
# April, June, September and November have 30 days.
# All others have 31 except February
case $MONTH in
"02")
# First we assume it's a normal February.
LAST_DAY=28
# Then we test if this is a leap year.
if [ $(date -d "$YEAR-02-29" > /dev/null 2>&1) ]
then
# It's a leap year
LAST_DAY=29
fi
;;
"04" | "06" | "09" | "11")
LAST_DAY=30
;;
*)
LAST_DAY=31
;;
esac
# 7 days from the end of the month.
START_OF_LAST_WEEK=$[ $LAST_DAY - 6 ]
if [ $TODAY -ge $START_OF_LAST_WEEK ] && [ $TODAY -le $LAST_DAY ]
then
# This is last week of the month.
exit 0
fi
;;
*)
echo "$0: Unknown argument. Was expecting: 1, 2, 3, 4, 5, l or L"
exit 2
;;
esac
# Not today
exit 1