How to increment a date in a Bash script

I have a Bash script that takes an argument of a date formatted as yyyy-mm-dd.

I convert it to seconds with

startdate="$(date -d"$1" +%s)";

What I need to do is iterate eight times, each time incrementing the epoch date by one day and then displaying it in the format mm-dd-yyyy.


Solution 1:

Use the date command's ability to add days to existing dates.

The following:

DATE=2013-05-25

for i in {0..8}
do
   NEXT_DATE=$(date +%m-%d-%Y -d "$DATE + $i day")
   echo "$NEXT_DATE"
done

produces:

05-25-2013
05-26-2013
05-27-2013
05-28-2013
05-29-2013
05-30-2013
05-31-2013
06-01-2013
06-02-2013

Note, this works well in your case but other date formats such as yyyymmdd may need to include "UTC" in the date string (e.g., date -ud "20130515 UTC + 1 day").

Solution 2:

startdate=$(date -d"$1" +%s)
next=86400 # 86400 is one day

for (( i=startdate; i < startdate + 8*next; i+=next )); do
     date -d"@$i" +%d-%m-%Y
done

Solution 3:

Just another way to increment or decrement days from today that's a bit more compact:

$ date %y%m%d ## show the current date
$ 20150109
$ ## add a day:
$ echo $(date %y%m%d -d "$(date) + 1 day")
$ 20150110
$ ## Subtract a day:
$ echo $(date %y%m%d -d "$(date) - 1 day")
$ 20150108
$ 

Solution 4:

Increment date in bash script and create folder structure based on Year, Month and Date to organize the large number of files from a command line output.

for m in {0..100}
do
    folderdt=$(date -d "Aug 1 2014 + $m days" +'%Y/%m/%d')
    procdate=$(date -d "Aug 1 2014 + $m days" +'%Y.%m.%d')
    echo $folderdt
    mkdir -p $folderdt
    #chown <user>:<group> $folderdt -R
    cd $folderdt
    #commandline --process-date $procdate
    cd -
done

Solution 5:

There is another way similar to this, may not be as fast as adding 86400 seconds to the day, but worth try -

day="2018-07-01"
last_day="2019-09-18"
while [[ $(date +%s -d "$day") -le $(date +%s -d "${last_day}") ]];do 
    echo $i;    
    # here you can use the section you want to use
    day=$(date -d "$day next day" +%Y-%m-%d); 
done