The Answer to Life, the Universe, and Everything

Wednesday, August 16, 2006

Shell Backup Script

Here is the shell script for backup of the server contents to another over scp.
#!/bin/sh
#################################################################
# Script for the backup the contents under the specified folder
# and the all mysql data
#
# -Cavalierski
#################################################################
# The Following setting should be modified for the each environment
##################################################################
#Date format of the back up file. This will be the prefix of the file
DATE_FORMAT=$(date +'%Y%m%d')

#Specify the folder that you want to backup
TARGET_DIR=(/var/www/xxx /home/xxx/test)

#Set the backup file name
BACKUP_LOGFILE=${DATE_FORMAT}.log
BACKUP_SQLFILE=${DATE_FORMAT}.sql.gz

#Setting for MySQL
MYSQL_PASSWD=

#Setting for Backup server over scp
SCPURL=www.loveanna.net:backup
SCPUSER=xxx

# Do not edit the below lines
##################################################################
# Temporary backup file
BACKUP_DIR=/tmp/www
function make_backup(){
for f in "$@"
do
if [ -d "$f" ]
then
tar zcvf ${BACKUP_DIR}/${DATE_FORMAT}_${f##/*/}.tar.gz "$f"/* >>
${BACKUP_DIR}/${BACKUP_LOGFILE}
else
echo "[ERROR] $f doesn't exist" >> ${BACKUP_DIR}/${BACKUP_LOGFILE}
fi
done

#The Answer to Life, the Universe, and Everything
return 42;
}

mkdir -p $BACKUP_DIR
make_backup ${TARGET_DIR[*]}
mysqldump -uroot --password=$MYSQL_PASSWD --all-databases | gzip>
$BACKUP_DIR/$BACKUP_SQLFILE

if [ $? -ne 0 ]
then
echo "[ERROR] sqldump failed" > ${BACKUP_DIR}/${BACKUP_LOGFILE}
fi

BKFILES=$(ls $BACKUP_DIR/${DATE_FORMAT}*)
BKNUM=${#BKFILES[@]}

for ((i=0;i<BKNUM;i++)); do
scp ${BKFILES[i]} ${SCPUSER}@${SCPURL}
rm -R ${BKFILES[i]:-${BACKUP_DIR}/*}
done