7

I am having issue storing my server backup on a storage VPS. My server is not deleting old backup folders and the storage is getting full and the backup fails in mid way. My runs once every week.

Can anyone help me create a cron job script on that deletes folder older than 7 days and runs one day before backup and delete old folders.

Any help appreciated.

Sohail Ahmed
  • 113
  • 1
  • 2
  • 7
  • There is one in the examples section of the `find` manpage. – wildplasser Jan 01 '17 at 16:01
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306) – jww Jan 02 '17 at 19:48

1 Answers1

22

For example, the description of crontab for deleting files older than 7 days under the /path/to/backup/ every day at 4:02 AM is as follows.

02 4 * * * find /path/to/backup/* -mtime +7 -exec rm {} \;

Please make sure before executing rm whether targets are intended files. You can check the targets by specifying -ls as the argument of find.

find /path/to/backup/* -mtime +7 -ls

mtime means the last modification timestamp and the results of find may not be the expected file depending on the backup method.

minamijoyo
  • 3,305
  • 1
  • 18
  • 20
  • There's no need to use -exec rm {} \; simply using the -delete flag is sufficient. – Space Bear Oct 04 '19 at 13:59
  • 2
    @SpaceBear yes, but this has a slightly different behaviour, as it would return an error state if `find` faces any problems to delete (for example the not empty folder). This could be a problem, if you want to use this as a simple logrotate job for example in Apache Airflow which expects exit 0 for a job to declare it as sucessfully run. So you have to use `... -exec rm {} \;` then – Jürgen Zornig Nov 18 '19 at 12:33