I’ve been putting off writing a proper backup script for ages but actually its not rocket science!
The goal was to keep a month of rolling backups, totally automatically. I decided, rather than fiddling around with date comparisions, to just name the backup after the day portion of the date, so a month’s worth of backups is always available (after the first month.)
The server is a Plesk server, so all sites sit below /var/www/vhosts/
Here’s the script, with comments:
#!/bin/sh
#create 2 filenames
SQLFILE=backup_`date '+%e'`.sql
TGZFILE=backup_`date '+%e'`.tgz
#get full db backup
cd /var/www/vhosts
#delete old one if there
rm /var/www/vhosts/$SQLFILE
mysqldump --opt --all-databases -uadmin -pMySQL_password > $SQLFILE
#backup web, including the DB backup we've just done
cd /var/www
#delete old one if its there
rm /var/www/$TGZFILE
#use --exclude to ignore big fat log files that you can cope without
tar -zcvf $TGZFILE --exclude '*statistic*' --exclude '*.log' vhosts
#ftp to backup server
#My FTP login is in /root/.netrc but you could add it here instead.
#You'd use this command instead: ftp -n
#Then you'd add "user $USERNAME $PASSWORD" straight below the <<EOF
ftp myftpserver.net <<EOF
del $TGZFILE
put $TGZFILE
quit
EOF
#now I just move them somewhere out of the way on the server, keeping a month's worth here too
rm /root/backups/$SQLFILE
mv /var/www/vhosts/$SQLFILE /root/backups/$SQLFILE
rm /root/backups/$TGZFILE
mv /var/www/$TGZFILE /root/backups/$TGZFILE
Tags: 3 Comments

By the way, in an ideal world you’d use SCP to shift the backup file offsite, being more secure as it is. My host provides separate backup space but with only FTP access, so that’s why I’m FTPing them out.
doh, %e gives date *space padded* which gets messy on the 1st of the month! - so use %d instead
Thanks a lot for the script. I used it with some modifications to automate backups on one of my servers.