#!/bin/bash # File: backup-myweb-with-ftp.sh # Author: A-Lang # Created: By 2012-09-03 # Define main variables BACKUPDIR="/root/myweb_backup" KEEP=5 # keep X latest backup files FTP_HOST='your.ftp.host.ip' FTP_ID='yourname' FTP_PW='123456' FTP_DEST='temp/test' DB_BK_FILE=DB_$(date +"%Y%m%d").tar.gz WWW_BK_FILE=WWW_$(date +%Y%m%d).tar.gz if [ -d $BACKUPDIR ]; then cd $BACKUPDIR else echo "Failed: The directory $BACKUPDIR not found." exit 1 fi # Remove the old files # Find out the latest X files # #CURRENT_COUNT=$(find . -not -type d -printf "%T+ %p\n" | sort -r | awk '{print $2}' | wc -l) CURRENT_COUNT=$(find . -name "*.tar.gz" -type f | xargs ls -lt | wc -l) if [ $CURRENT_COUNT -gt $KEEP ]; then OLD_COUNT=$(($CURRENT_COUNT - $KEEP)) OLD_FILES="" for f in $(find . -name "*.tar.gz" -type f | xargs ls -lt | tail -$OLD_COUNT | awk '{print $9}');do OLD_FILES="$OLD_FILES `basename $f`" done rm -f $OLD_FILES else OLD_COUNT=0 OLD_FILES="" fi # Backup the DB /usr/bin/mysqldump -u root -ppassw0rd mya2billing > $BACKUPDIR/mya2billing.sql # Archive the backup file for DB tar zcf $DB_BK_FILE *.sql rm -rf *.sql # Backup the Web-Root directory #tar zcvf $BACKUPDIR/$WebBakName /home/wwwroot # Purge the old files on FTP site if [ $OLD_COUNT -gt 0 ] && [ -n "$OLD_FILES" ]; then ftp_purge_cmd="/tmp/ftp_purge_$$.tmp" echo " open $FTP_HOST user $FTP_ID $FTP_PW type binary cd $FTP_DEST" > $ftp_purge_cmd for x in $OLD_FILES;do echo "delete $x" >> $ftp_purge_cmd done echo "bye" >> $ftp_purge_cmd ftp -v -n < $ftp_purge_cmd rm -f $ftp_purge_cmd sleep 1 fi # Upload the backup files ftp_upload_cmd="/tmp/ftp_upload_$$.tmp" echo " open $FTP_HOST user $FTP_ID $FTP_PW type binary cd $FTP_DEST put $DB_BK_FILE bye" > $ftp_upload_cmd ftp -v -n < $ftp_upload_cmd rm -f $ftp_upload_cmd