Basically we need to set up a script and run that in “Cron” which is a linux tool that allows commands/scripts to be run at set intervals.
- First create a directory in your root level / (in a Linux environment with cPanel this will be one level higher than public_html) and name it /backups.
- Create a file called backup.sh in /backups, either through a simple text editor like NotePad/TexEdit or TextWrangler or via Vi or Pico in the command line and paste the following:
#!/bin/bash
tar czf ~/backups/backup_`date +%Y_%m_%d`.tgz ~/public_html
This tells Linux that is a command and will save a compressed zipped file and file it in your /backups folder, name it backup_Year/Month/Day and it is backing up the entire contents of the /public_html folder.
- Change the file permissions of backup.sh to 700 so just the owner has read/write/execute permissions. Do this through either file manager in cPanel or FTP .
- The final thing to do is to set this script/command to run automatically in Cron in your cPanel. Log into your cPanel and scroll to Advanced and click on Cron:
cron-in-cpanel-backup
And in the resulting screen, add your email address in, the frequency of the backup, once a day should be fine and lastly and most importantly in the command field –
~/backups/backup.sh
Click add New Cron Job and all should be OK.
cron-settings-backup-cpanel
Look in your /backups folder to see if the backup completed – any errors will be redirected to your email.
Doing it this way will make a cumulative back ups per day eventually filling up your allowed hard disk quota, you either can either manually mange this issue by deleting old back ups periodically or you can adjust the script so only a recent back up is kept.
This can be acheieved by making an extra line to the script:
#!/bin/bash
rm -rf ~/backups/*
tar czf ~/backups/backup_`date +%Y_%m_%d`.tgz ~/public_html
So the additional line “rm -rf ~/backups/*” will remove any previous backups prior to backing up the site so only one daily back up is available. – Make sure you get the tilde “~” in there! The tilde represents your home folder.
Taking this concept a step further would be to keep a daily, a weekly and a monthly back up on hand; so you would create three directories first at your root level such as at /public_html/:
/backups/daily/
/backups/weekly/
/backups/monthly/
Create three scripts:
backupdaily.sh:
#!/bin/bash
rm -rf ~/backups/daily/*
tar czf ~/backups/daily/backup_`date +%Y_%m_%d`.tgz ~/public_html
backupweekly.sh:
#!/bin/bash
rm -rf ~/backups/weekly/*
tar czf ~/backups/weekly/backup_`date +%Y_%m_%d`.tgz ~/public_html
backupmonthly.sh:
#!/bin/bash
rm -rf ~/backups/monthly/*
tar czf ~/backups/monthly/backup_`date +%Y_%m_%d`.tgz ~/public_html
Last thing to do is to add the three scripts as “cron” jobs following the previous steps above and set the schedules to daily, weekly and monthly to the relevant back up scripts.