Bash: How to Increment a Date


Often you may want to increment dates in Bash.

You can use the following methods to do so:

Method 1: Increment Date Variable by One Day

next_date=$(date +%m-%d-%Y -d "$my_date + 1 day")

This particular example will create a new variable named next_date that increments the existing date in the my_date variable by one day.

Method 2: Increment Date in For Loop

for i in {0..10}
do
   next_date=$(date +%m-%d-%Y -d "$my_date + $i day")   
   echo "$next_date"
done

This particular example increments the date in the existing my_date variable by one day and repeats the process 10 times using a for loop.

The following examples show how to use each method in practice.

Example 1: Increment Date Variable by One Day in Bash

Suppose that we create a date variable named my_date that contains the date 2024-08-22.

We can use the following syntax to create a new variable named new_date that increments this date by one day.

my_date=2024-08-22
next_date=$(date +%m-%d-%Y -d "$my_date + $1 day")

echo $next_date

The following screenshot shows how to use this syntax in practice:

Bash increment date by one day

Notice that when we use the echo statement we can see that the date stored in the next_date variable is equal to 08-23-2024, which represents the date stored in the my_date variable incremented by one day.

Example 2: Increment Date in For Loop in Bash

Suppose that we create a date variable named my_date that contains the date 2024-08-22.

We can use the following syntax to increment this date by one day and use a for loop to repeat the process 10 times:

my_date=2024-08-22

for i in {0..10}
do
   next_date=$(date +%m-%d-%Y -d "$my_date + $i day")   
   echo "$next_date"
done

The following screenshot shows how to use this syntax in practice:

Bash increment date in for loop

Notice that this returns the date stored in the my_date variable along with the next 10 consecutive dates.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Convert Timestamp to Date in Bash
How to Calculate Date Difference in Bash
How to Compare Dates in Bash

Leave a Reply