views:

33

answers:

2

I have the following simple script for backing up my website files and db. The script is run each day via a cron job.

#!/bin/sh

NOW=$(date +"%Y-%m-%d")

mysqldump --opt -h localhost -u username -p'password' dbname > /path/to/folder/backup/db-backup-$NOW.sql

gzip -f /path/to/folder/backup/db-backup-$NOW.sql

tar czf /path/to/folder/backup/web-backup-$NOW.tgz /path/to/folder/web/content/

It works great, but I don't want loads of old backups clogging my system. How can I modify the script to remove any backups older than a week when the script is run?

A: 

How about adding something like this:

find -ctime +7 -print0 | xargs -0 rm -v

find -ctime +7 -print0 finds all files that were changed (the c) more than 7 days ago (+7) and sends that out as a \0 separated string (-print0) which xargs -0 sends to rm -v as arguments.

WoLpH
Thank you for your quick response. Could you explain exactly what that code does? I am a but new to perl. I just want to understand what each part of that is doing.
Robert Robb
@Robert Robb: That is not Perl code. That line could be added directly to your shell script. Read the manpage for the shell `find` command using `man find` at your shell prompt. Likewise: `man xargs`.
toolic
@Robert Robb: will this explanation help?
WoLpH
Thanks all. Great.
Robert Robb
`-ctime` is the time a file was changed not when it was created. The time a file was created is not saved.
Dennis Williamson
@Dennis, right. It's `change time`, `modified time` and `access time`. I'll edit my answer.
WoLpH
A: 

with GNU find, you can use -delete

find /path -type f -iname "*backup*gz" -mtime +7 -delete

or you can use +; in place of xargs.

find /path -type f -iname "*backup*gz" -mtime +7 -exec rm -f "{}" +;
ghostdog74
Thanks, I am going to give that a try too.
Robert Robb