How to append date to filename, but base it on yesterday's date?

Hello,

I'd like to write a monthly archive script that archives some logs. But I'd like to do it based on yesterday's date. In other words, I'd like to schedule the script to run on the 1st day of each month, but have the archive filename include the previous month instead.

Here's what I have so far (this works for current day):

#!/bin/bash
cd /home/logs
tar cvzf /home/logs/logarchives_`date +%Y-%m\(%b\)`.tar.gz *.log

So the format ends up being: filename_2013-09(Sep).tar.gz
I'd like to be able to run a script on October 1st and have it say that.
And I'd like to run the same script on November 1st and have it end up with a filename_2013-10(Oct).tar.gz

Thanks!

Does your date allow for the -d option:

date -d"-1day"
Mi 18. Sep 19:46:18 CEST 2013

or even date -dy y meaning yesterday.

1 Like

Thanks!

This seems to work:

#!/bin/bash
cd /home/logs
tar cvzf /home/logs/logarchives_`date -dy +%Y-%m-%d`.tar.gz *.log

So I will test at the end of the month with:

#!/bin/bash
cd /home/logs
tar cvzf /home/logs/logarchives_`date -dy +%Y-%m\(%b\)`.tar.gz *.log

:slight_smile:

Just adding my 2 cents here.
Since we're still 10 days from the end of the month, you could temporarily change the date and time of your system to perform your test in advance:

date --set="1 OCT 2013 00:00:01"

Afterwards you can set the right date and time.
Just saying ;).

1 Like

Why shouldn't above work across month ends? Run it today with -d "-20 days" to test.

1 Like

RudiC, to confirm, that would look like:

tar cvzf /home/logs/logarchives_`date -d "-20 days" +%Y-%m\(%b\)`.tar.gz *.log

Correct?

---------- Post updated at 02:14 PM ---------- Previous update was at 02:11 PM ----------

That worked! Thanks everybody!