AWS EC2 Linux: Simple backup script

I have a small EC2 box running a couple of WordPress sites. To back them up I wrote a quick bash script that dumps out the databases and also zips up all the files. This script is running daily, the amount of disc space doesn’t really matter since the sites are really small. If you have larger sites you might want to split the script into one for weekly backup for files and a daily one for databases, the principal are the same.
Prerequisites
- Credentials for MySQL with access to the database in question. In this example I run with root.
- A folder where you want to store your backups. You should a separate folder since we clean out old backups in the script.
- Path to the www root folder for the sites.
Script
First we create a script and open it for editing in nano:
[bash]nano backup.sh[/bash]
First line in any bash script is:
[bash]#! /bin/bash[/bash]
Then we create a variable to keep the current date:
[bash]_now=$(date +"%m_%d_%Y")[/bash]
Then we dump out the databases to .sql files:
[bash]
mysqldump –user root –password=lamedemopassword wp_site_1 > /var/www/html/backup/wp_site_1_$_now.sql
mysqldump –user root –password=lamedemopassword wp_site_2 > /var/www/html/backup/wp_site_2_$_now.sql
[/bash]
Here we use the $_now variable we declared in the beginning of the script. So we can easily find the correct backup if we need to do a restore. Next step is to zip up the www contents of each site:
[bash]
tar -zcvf /var/www/html/backup/www_backup_site1_$_now.tar.gz /var/www/html/wp_site_1
tar -zcvf /var/www/html/backup/www_backup_site2_$_now.tar.gz /var/www/html/wp_site_2
[/bash]
Once again we use the $_now variable to mark the file name with the current date for the backup.
Then we want to clean out backups older then x days. In this example I remove all backup files older then 7 days.
[bash]
find /var/www/html/backup/* -mtime +7 -exec rm {} ;
[/bash]
The first part find /var/www/html/backup/* -mtime +7 then we use the -exec to pipe the result into a command, in this case rm. The {} inserts the files found and the escapes the command to prevent it to expand the shell. Then we finalize the row with a ;. So this means that for each file found it will execute the rm command and remove that file.
Save the backup.sh file and exit nano. Now we need to make the script executable:
[bash]chmod 755 backup.sh[/bash]
Then we can do a test run of the script:
[bash]sudo ./backup.sh[/bash]
Now check the folder that the files was created and contain the actual data. If your satisfied with the result you can move the script into the cron.daily folder.
[bash]sudo mv /home/ec2-user/backup.sh /etc/cron.daily/[/bash]
Now the daily cronjob will create a backup of the WordPress sites. Both files and databases.