Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a date in a Bash script

Tags:

date

bash

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.

like image 701
JAyenGreen Avatar asked Sep 09 '13 20:09

JAyenGreen


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I echo date in bash script?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.


2 Answers

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").

like image 54
swdev Avatar answered Oct 08 '22 14:10

swdev


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 
like image 32
Aleks-Daniel Jakimenko-A. Avatar answered Oct 08 '22 15:10

Aleks-Daniel Jakimenko-A.