Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last month? date +%Y%m -d '1 month ago' doesn't work on March 30

Tags:

date

linux

bash

I wrote a script to delete old files. Part of the script is following:

lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then        
    rm -Rf $inputdir0
fi

There are some directories named after the date +%Y%m%d format. Now it's March 29/30/31 and the script deleted all files of this month. Today I learned this happens because there is no February 29/30/31.

How can i fix this?

like image 724
mbergmann Avatar asked Oct 19 '25 01:10

mbergmann


2 Answers

Subtract the number of days in the current month, and you will get the last day of the previous month. For example:

date +%Y-%m-%d -d "`date +%d` day ago"

results in

2017-02-28

Since you don't care about the day and only want the month, you will always get the correct month:

lastmonth=$(date +%Y%m -d "$(date +%d) day ago")
like image 148
fancyPants Avatar answered Oct 21 '25 13:10

fancyPants


If you wish to get the date shifted by number of days you provide :

Number=222
current_date=$(date +%Y%m%d)
past_date=$(date -d "$current_date - $Number days" +%Y%m%d)
echo "$current_date\t$past_date"

If you wish to get for 1 month :

date -d "$current_date -1 month"

Similarily for one year :

date -d "$current_date -1 year"
like image 21
Ashish K Avatar answered Oct 21 '25 13:10

Ashish K