This blog post contains a bash script that prints out dates betwen a range of dates.
Scenario and Use Case
I want to write a bash script that accepts as arguments a starting date and ending date, both in the format YYYY-MM-DD
.
In the below example, I want to make the script print dates from January 28, 2020 through February 6, 2020, and including both the start and end dates.
Usage
./daterange.sh 2020-01-28 2020-02-06
Output
2025-01-28 2025-01-29 2025-01-30 2025-01-31 2025-02-01 2025-02-02 2025-02-03 2025-02-04 2025-02-05 2025-02-06
Create bash script
Create an empty shell script daterange.sh and add these lines as contents:
#!/bin/bash
#
# Bash script to print list of dates from starting date to ending date
# Written by Arul John
# Blog Post: https://aruljohn.com/blog/bash-sequence-of-dates/
#
# Accept arguments -- start date and end date
if [[ $# -lt 2 ]] ; then
echo "USAGE: $0 <START-DATE> <END-DATE>"
exit 0
fi
# Get start date and end date and convert both to their epoch dates
start_date=$(date --date "$1" +%s)
end_date=$(date --date "$2" +%s)
# Loop through both dates and print all dates in between
while [[ "$start_date" -le "$end_date" ]]; do
current_date="$(date -d "$(date -d @$start_date)" -I)"
echo "$current_date"
start_date=$((start_date + 86400))
done
How this script works
We create the Unix timestamp or epoch from the string value of the date.
For example, to find today's date, use date -I
. We will find the epoch / Unix timestamp for it.
today=$(date -I)
echo $(date --date "$today" +%s)
Output:
1739336400
In the script, after printing the current date, we add 86400 seconds to proceed to the next date. This continues until we complete the end date.
Add execute permission and run without arguments
Chmod the script to 755:
chmod 755 daterange.sh
Run it without any arguments, to see the usage:
$ ./daterange.sh
USAGE: ./daterange.sh <START-DATE> <END-DATE>
Test the bash script
Run it with arguments:
$ ./daterange.sh 2020-02-10 2020-02-15
2020-02-10
2020-02-11
2020-02-12
2020-02-13
2020-02-14
2020-02-15
Conclusion
This is only one out of many methods of finding dates in a date range. There are many other ways of doing it, but this is my favorite, hence this blog post.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.