Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Created July 27, 2021 19:15
Show Gist options
  • Save blaylockbk/353bb5430e955fa25ac34364996915fe to your computer and use it in GitHub Desktop.
Save blaylockbk/353bb5430e955fa25ac34364996915fe to your computer and use it in GitHub Desktop.
Loop over dates in a Bash script
#!/bin/bash
#=======================================================================
# Specify the "start" and "end" time.
#=======================================================================
# Use format "HH:MM YYYY-MM-DD"
start="00:00 2021-04-01"
end="00:00 2021-04-02"
increment="+1 hours"
#=======================================================================
# Convert start and end time to full Bash datetime format
# For example, it converts "00:00 2021-04-01" to "Thu Apr 1 00:00:00 GMT 2021"
start=$(date -d "${start}")
end=$(date -d "${end}")
# The below while statement will loop over each date between the start and
# end time. Each loop will increment the date by "+1 hours" (defined above).
# NOTE: The +%s in the first line converts the date to "seconds since
# EPOC" which makes the comparison between start and end time possible.
# See bottom of page here: https://phoenixnap.com/kb/linux-date-command
while (( $(date -d "${start}" +%s) <= $(date -d "${end}" +%s) )); do
echo #< empty echo statement prints a blank line
echo Current Loop Date: ${start}
# DO SOME STUFF WITH THE DATE
# Increment the value. This changes the value of `$start` every loop
# with the next date.
start=$(date -d "${start} ${increment}")
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment