I have two arguments as inputs: startdate=20160512
and enddate=20160514
.
I want to be able to generate the days between those two dates in my bash script, not including the startdate, but including the enddate:
20160513 20160514 I am using linux machine. How do I accomplish this? Thanks.
To format date in DD-MM-YYYY format, use the command date +%d-%m-%Y or printf "%(%d-%m-%Y)T\n" $EPOCHSECONDS .
Using 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, spread over multiple 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
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 20160514
20160512
20160513
20160514
$ dateseq 2016-05-12 2016-05-14
2016-05-12
2016-05-13
2016-05-14
This should work on OSX, make sure your startdate is lesser than enddate, other wise try with epoch.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With