0

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?

1
  • 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. Commented May 22, 2018 at 17:36

1 Answer 1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.