我想要 UNIX 中日期 2018-03-28 到 2018-04-02 的 while 循环语法
答案1
根据评论中用户的意愿进行编辑以使用YYYYMMDD
输出格式而不是格式,并添加也取自评论的开始日期和结束日期变量。YYYY-MM-DD
假设 GNU date
:
startdate='2018-03-28'
enddate='2018-04-02'
enddate=$( date -d "$enddate" +%Y%m%d ) # rewrite in YYYYMMDD format
i=0
while [ "$thedate" != "$enddate" ]; do
thedate=$( date -d "$startdate + $i days" +%Y%m%d ) # get $i days forward
printf 'The date is "%s"\n' "$thedate"
i=$(( i + 1 ))
done
或者:
startdate='2018-03-28'
enddate='2018-04-02'
enddate=$( date -d "$enddate + 1 day" +%Y%m%d ) # rewrite in YYYYMMDD format
# and take last iteration into account
thedate=$( date -d "$startdate" +%Y%m%d )
while [ "$thedate" != "$enddate" ]; do
printf 'The date is "%s"\n' "$thedate"
thedate=$( date -d "$thedate + 1 days" +%Y%m%d ) # increment by one day
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"