Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate all dates between two dates in %Y-%m-%d-%H format in bash

Using bash I want to generate all dates between, say, 2023-11-04-00 and 2023-11-06-00 where the format is %Y-%m-%d-%H. I have tried :

#!/bin/bash

d=2023-11-04
while [ "$d" != 2023-11-06 ]; do
        d=$(date -d "$d 1 hour")
        u=$(date -d "$d" +'%Y-%m-%d-%H')
        echo $u
done

It works but I get an infinite loop and can’t quite figure out what is happening.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Let’s have a look at what $d actually looks like:

$ d=2023-11-04
$ d=$(date -d "$d 1 hour")
$ echo "$d"
Sat Nov  4 01:00:00 AM EDT 2023

Oh. That’s not a string that’s ever going to be equal to 2023-11-06.

Let’s see if we can fix that:

#!/bin/bash

d=2023-11-04
while [ "$(date -d "$d" +'%Y-%m-%d')" '<' 2023-11-06 ]; do
        d=$(date -d "$d 1 hour")
        u=$(date -d "$d" +'%Y-%m-%d-%H')
        echo $u
done

Much better.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading