makansij
makansij

Reputation: 9865

How to iterate through dates from start date to end date?

I have to move files over a very large date range (from 20141212 to 20170202).

How do I iterate over all of these dates in the format %Y%m%d in bash on a unix machine?

I'm using the gnu version of date.

Upvotes: 1

Views: 3396

Answers (2)

hroptatyr
hroptatyr

Reputation: 4809

With the help of a 3rd party tool (dateutils):

$ dateseq -i %Y%m%d 20141212 20170202 -f %Y%m%d
20141212
20141213
20141214
20141215
20141216
20141217
20141218
20141219
...

The -i and -f options are necessary to deal with your specific format.

Disclaimer: I am the author of the package.

Upvotes: 2

Chris
Chris

Reputation: 1623

For a hilariously inefficient way of doing things:

for x in {20141212..20170202}
do
date --date="$x" &> /dev/null && whateverCommand "$x"
done

For a quicker way:

x=0
while :
do
thisDate=`date --date="20141212 $x days" +%Y%m%d`
whateverCommand $thisDate
if [[ $thisDate = 20170202 ]]; then break; fi
((x++))
done

Upvotes: 4

Related Questions