mbergmann
mbergmann

Reputation: 95

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

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?

Upvotes: 4

Views: 11260

Answers (2)

fancyPants
fancyPants

Reputation: 51868

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

Upvotes: 7

Ashish K
Ashish K

Reputation: 935

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"

Upvotes: 3

Related Questions