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

I have two arguments as input: startdate=20160512and enddate=20160514.

I want to be able to generate days between these two dates in my bash script, not including the start date, but including enddate:

20160513 20160514 I am using a Linux machine. How to do it? Thank you

+4
source share
3 answers

Using the GNU Date:

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

Or, a few lines:

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

How it works

  • d=; n=0

    Initialize variables.

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

    Run a loop that ends on enddate.

  • ((n++))

    Increase the day counter.

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

    Calculate the date ndays after startdate.

  • echo $d

    Display date.

  • done

    End of cycle signal.

+8

OSX, , , enddate, .

startdate=20160512
enddate=20160514

loop_date=$startdate

let j=0
while [ "$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+1
done
+1

Another option is to use dateseqfrom dateutils( http://www.fresse.org/dateutils/#dateseq ). -ichanges the input format, and -fchanges the output format.

$ dateseq -i%Y%m%d -f%Y%m%d 20160512 20160514
20160512
20160513
20160514
$ dateseq 2016-05-12 2016-05-14
2016-05-12
2016-05-13
2016-05-14
+1
source

All Articles