How does the "1 month ago" option in date command work?

- 1 month will subtract one from the month number, and then if the resulting date is not valid (February 30, for example), adjust it so that it is valid. So December 31 - 1 month is December 1, not a day in November, and March 31 - 1 month is March 3 (unless executed in a leap year).

Here's quote from the info page for Gnu date (which is the date version which implements this syntax), which includes a good suggestion to make the arithmetic more robust:

The fuzz in units can cause problems with relative items. For example, 2003-07-31 -1 month might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

    $ date -R
    Thu, 31 Jul 2003 13:02:39 -0700
    $ date --date='-1 month' +'Last month was %B?'
    Last month was July?
    $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
    Last month was June!

Another warning, also quoted from the info page:

Also, take care when manipulating dates around clock changes such as daylight saving leaps. In a few cases these have added or subtracted as much as 24 hours from the clock, so it is often wise to adopt universal time by setting the TZ environment variable to UTC0 before embarking on calendrical calculations.


Instead of relying on filenames for purging your backup files, you'd be safer relying on their time metadata.

For example you can delete all files older than 30 days with this command :

/usr/bin/find /path/to/your/files -type f -ctime +30 -delete

As a free bonus, running this everyday will allow you to keep your backup files on a rolling month, allowing a better disk space management.

For keeping 1st or 15th files, you could either store them in another directory, either update the find command with -not -name option.

Tags:

Date

Coreutils