While 循环产生错误的日​​期

While 循环产生错误的日​​期

我有以下循环,但它不会停止并产生错误的日​​期。

#!/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

我期望这个输出:

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

我怎样才能实现这个目标?

答案1

i你根本不需要柜台。
您只需在每次迭代中将当前日期增加 1 即可。

#!/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

相关内容