Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 601
  • Last Modified:

On Ubuntu how do I use CRON to backup my sites and delete old backups at the same time?

Hi all,

I have a ubuntu 14.04 x64 distribution on a Linode VPS with Apache 2.4.7 and mySQL server 5.5.

I have several working sites on my server already and I need to have some automatic system that could do the following:

At 4 am GMT (my system clock is set to GMT) every day I need certain folders to be gzipped and sent to a specific backup folder. I also need the script to keep the last 7 copies only (including current file) and delete the oldest file within the backup folder.

Working example:-
ORIGIN: /home/myuser/public/mysite.com/public
DESTINATION: /home/myuser/public/_DB_BACKUP/mysite.com/mysite.com_yyyy-mm-dd.gz

Could anyone please assist? I have no experience with CRON or .sh scripts and I have only started using linux last month.

thanks in advance
1 Solution
You also can't just gzip a folder.  You'll need tar.  There's also a call to the date command to insert the date into the file name.  It uses the backquote (`) which has a different meaning than the single quote (').

tar -czf /home/myuser/public/_DB_BACKUP/mysite.com/mysite.com_`date "+%Y-%m-%d%n"`.tar.gz /home/myuser/public/mysite.com/public

Open in new window

Here's a quick way to find and delete the older file
find /home/myuser/public/_DB_BACKUP/mysite.com/ -mtime 7 -exec rm {} \;

Open in new window

You can then add them to cron.  This sets the backup to start every midnight.
0 0 * * * /bin/tar -czf /home/myuser/public/_DB_BACKUP/mysite.com/mysite.com_`/bin/date "+%Y-%m-%d%n"`.tar.gz /home/myuser/public/mysite.com/public; /usr/bin/find /home/myuser/public/_DB_BACKUP/mysite.com/ -mtime 7 -exec rm {} \;

Open in new window

crontab quick reference  http://www.adminschoice.com/crontab-quick-reference/

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now