Last active
April 8, 2025 08:31
-
-
Save therightstuff/85292fc99c068a03c3618b02341f44bb to your computer and use it in GitHub Desktop.
A shell script to test whether the current time is between two given times
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
#!/usr/bin/env sh | |
# A script that receives start and end parameters in the format HH:mm and | |
# exit with an error code if the current time is not within the desired | |
# window. | |
# The given times are not inclusive, so if you want 06:00-10:00 inclusive | |
# you need to specify 05:59 and 10:01 respectively. | |
# This script assumes that we are interested in time periods shorter than | |
# a single day, and it handles overnight periods. | |
# Inspired by https://unix.stackexchange.com/a/395936/305967 | |
# eg. | |
# $ ./in_between.sh 10:15 11:45 | |
# $ ./in_between.sh 21:00 06:30 | |
current_time=$(date +%H:%M) | |
start_time="$1" | |
end_time="$2" | |
echo "Checking current_time ${current_time} is between ${start_time} and ${end_time}..." | |
is_between=false | |
if [ "$end_time" \> "$start_time" ]; then | |
if [ "$current_time" \> "$start_time" ] && [ "$current_time" \< "$end_time" ]; then | |
is_between=true | |
fi | |
else | |
if [ "$current_time" \> "$start_time" ] || [ "$current_time" \< "$end_time" ]; then | |
is_between=true | |
fi | |
fi | |
if [ $is_between = true ]; then | |
echo "$current_time is between $start_time and $end_time" | |
else | |
echo "$current_time is not between $start_time and $end_time" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment