Shell gets the date N days/month/before (and after) the specified date

0 Preface

Sometimes when we write batch shell scripts, we may need to get the date N days/month/year before (after) the specified date, where N can be 1 day/month/year, 2 days/month/year, 3 days /Month/year and so on. The method is actually very simple, here is a simple record. Based on this grammar, we can also write a loop to process all the data within N days of the specified date.

1. Get N days before (after) date

The first is to get the current date:

DATE=$(date +%Y%m%d)

This command will be DATEassigned to 20,190,904, %Y%m%dit is the format of this date, as well as the corresponding %Y%m(year, month, as 201,909), more of a search can search your own wording.

Get the date N days after this date ( ${DATE}can be replaced by any change date, such as 20190101):

DATE_TMP=$(date -d "${DATE} N days" "+%Y%m%d")

Get the date before and after this date N ( ${DATE}can be replaced by any change date, such as 20190101):

DATE_TMP=$(date -d "${DATE} N days ago" "+%Y%m%d")

for example:

Get the date 1 day after the current date:

DATE_TMP=$(date -d "${DATE} 1 days" "+%Y%m%d")

Get the date 1 day before the current date:

DATE_TMP=$(date -d "${DATE} 1 days ago" "+%Y%m%d")

learn by analogy:

Get the date N months after this date:

DATE_TMP=$(date -d "${DATE} N month" "+%Y%m%d")

Get the date N months before this date:

DATE_TMP=$(date -d "${DATE} N month ago" "+%Y%m%d")

Get the date N years after this date:

DATE_TMP=$(date -d "${DATE} N year" "+%Y%m%d")

Get the date N years before this date:

DATE_TMP=$(date -d "${DATE} N year ago" "+%Y%m%d")

2. Circulate data within N days

A simple way of writing a Shell script that processes data within N days of a specified date:

DATE=$(date +%Y%m%d)
for i in {1..5}
do
    DATE_TMP=$(date -d "${DATE} ${i} days ago" "+%Y%m%d")
    cd /root/backup
    rm -rf *${DATE_TMP}*
done

Based on this script, combined with the Linux crontab command (usage: Linux uses crontab to implement timing task format and usage introduction ), it is possible to delete data within 5 days of the current date, for example, every 7 days.

Note: This article is transferred from https://laowangblog.com/shell-get-specific-date.html

Guess you like

Origin blog.csdn.net/godlovedaniel/article/details/109264746