0

This question already has an answer here:

I have the following loop, but it doesn't stop and produces the wrong dates.

#!/bin/bash
i=0
thedate="2018-03-28"
enddate="2018-04-02"
while [ "$thedate" != "$enddate" ]; do
    thedate=$( date -d "$thedate + $i days" +%F )

    new_date=$( date -d "$thedate " +%Y%m%d )
    printf 'The date is "%s"\n' "$new_date"
    i=$(( i + 1 ))
done

I expected this output:

The date is "20180328"
The date is "20180329"
The date is "20180330"
The date is "20180331"
The date is "20180401"
The date is "20180402"

How can I achieve this?

marked as duplicate by Kusalananda bash May 22 '18 at 18:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Add set -x just before the start of the while loop, and verify that your script is doing what you really think it's doing. – DopeGhoti May 22 '18 at 17:36
1

You don't need the counter i at all.
You just need to increment the current date by 1 in every iteration.

#!/bin/bash
thedate="2018-03-28"
enddate="2018-04-02"
while [ "$thedate" != "$enddate" ]; do
    thedate=$( date -d "$thedate + 1 days" +%F )

    new_date=$( date -d "$thedate " +%Y%m%d )
    printf 'The date is "%s"\n' "$new_date"
done

Not the answer you're looking for? Browse other questions tagged or ask your own question.