How to print dates between two dates in format %Y%m%d in shell script? How to print dates between two dates in format %Y%m%d in shell script? shell shell

How to print dates between two dates in format %Y%m%d in shell script?


Using GNU date:

$ d=; n=0; until [ "$d" = "$enddate" ]; do ((n++)); d=$(date -d "$startdate + $n days" +%Y%m%d); echo $d; done2016051320160514

Or, spread over multiple lines:

startdate=20160512enddate=20160514d=n=0until [ "$d" = "$enddate" ]do      ((n++))    d=$(date -d "$startdate + $n days" +%Y%m%d)    echo $ddone

How it works

  • d=; n=0

    Initialize variables.

  • until [ "$d" = "$enddate" ]; do

    Start a loop that ends on enddate.

  • ((n++))

    Increment the day counter.

  • d=$(date -d "$startdate + $n days" +%Y%m%d)

    Compute the date for n days after startdate.

  • echo $d

    Display the date.

  • done

    Signal the end of the loop.


Another option is to use dateseq from dateutils (http://www.fresse.org/dateutils/#dateseq). -i changes the input format and -f changes the output format.

$ dateseq -i%Y%m%d -f%Y%m%d 20160512 20160514201605122016051320160514$ dateseq 2016-05-12 2016-05-142016-05-122016-05-132016-05-14


This should work on OSX, make sure your startdate is lesser than enddate, other wise try with epoch.

startdate=20160512enddate=20160514loop_date=$startdatelet j=0while [ "$loop_date" -ne "$enddate" ]; do        loop_date=`date   -j -v+${j}d  -f "%Y%m%d" "$startdate" +"%Y%m%d"`        echo $loop_date        let j=j+1done