Last active
July 22, 2020 15:25
-
-
Save basinilya/260096d9b90caf0044c5193ef00efd98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if the current time falls within defined time range on UNIX | |
#set -e | |
set -o pipefail | |
function errtrap { es=$?; echo "ERROR line $1: Command exited with status $es.">&2; exit 1; }; trap 'errtrap $LINENO' ERR | |
#export TZ=Asia/Kolkata | |
within() { ( | |
set +x | |
set -e | |
#export TZ=Asia/Kolkata | |
beg=${1:?} | |
end=${2:?} | |
if [ -z "$3" ]; then | |
now=`date +%s` | |
else | |
now=`date +%s -d "$3"` | |
fi | |
today=`date +%F -d@${now:?}` | |
if ! end1=`date +%s -d"${today:?} ${end:?}" 2>/dev/null`; then | |
tomorrow=`date +%F -d"${today:?} 1 days"` | |
end1=`date +%s -d"${tomorrow:?} ${end:?} 1 days ago"` | |
end2=`date +%s -d"${tomorrow:?} ${end:?}"` | |
else | |
end2=`date +%s -u -d "1970-01-01 $end1 seconds 1 days"` | |
fi | |
if ! beg2=`date +%s -d"${today:?} ${beg:?}" 2>/dev/null`; then | |
yesterday=`date +%F -d"${today:?} 1 days ago"` | |
beg2=`date +%s -d"${yesterday:?} ${beg:?} 1 days"` | |
fi | |
if ((beg2 < end1)); then | |
beg1=$beg2 | |
else | |
beg1=`date +%s -u -d "1970-01-01 $beg2 seconds 1 days ago"` | |
fi | |
realbeg=$(( now >= beg2 ? beg2 : beg1 )) | |
realend=$(( realbeg > end1 ? end2 : end1 )) | |
if (( now >= realbeg && now < realend )); then | |
echo "Exiting because `date --iso-8601=seconds -d@$realbeg` <= `date --iso-8601=seconds -d@$now` < `date --iso-8601=seconds -d@$realend`" | |
exit 1 | |
fi | |
exit 0 | |
)} | |
t() { | |
within "$@" | |
} | |
f() { | |
! t "$@" | |
} | |
export TZ=Europe/Berlin | |
t "02:01" "02:03" "2020-03-29T05:01" | |
f "02:01" "02:03" "2020-03-30T02:02" | |
#set -x | |
export TZ=Asia/Kolkata | |
f 23:00 06:30 03:00 | |
t 23:00 06:30 13:00 | |
f "0:01 IST" "0:00 IST" "2020-07-19 0:01 IST" | |
f "13:01 IST" "13:00 IST" "2020-07-19 0:01 IST" | |
f "0:01 IST" "0:00 IST" "2020-07-19 0:01 IST" | |
f "0:01 IST" "0:00 IST" "2020-07-19 0:02 IST" | |
f "0:01 IST" "0:00 IST" "2020-07-19 23:59 IST" | |
t "0:01 IST" "0:00 IST" "2020-07-19 0:00 IST" | |
t "11:30PM IST" "2:30AM IST" "2020-07-19 23:29 IST" | |
f "11:30PM IST" "2:30AM IST" "2020-07-19 23:30 IST" | |
f "11:30PM IST" "2:30AM IST" "2020-07-19 0:00 IST" | |
f "11:30PM IST" "2:30AM IST" "2020-07-19 2:29 IST" | |
t "11:30PM IST" "2:30AM IST" "2020-07-19 2:30 IST" | |
t "11:30PM IST" "11:40PM IST" "2020-07-19 23:29 IST" | |
f "11:30PM IST" "11:40PM IST" "2020-07-19 23:30 IST" | |
f "11:30PM IST" "11:40PM IST" "2020-07-19 23:39 IST" | |
t "11:30PM IST" "11:40PM IST" "2020-07-19 23:40 IST" | |
echo ok |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment