Monday, August 17, 2015

Sample bash backup script

I made a backup script using bash, this script will backup html directory and skip some folder that do not need to be included. The backup process will be written in the log file, so that we know whether backup running successfully or not.

Variable that needed to be changed:
LOG: the log file.
TEMPDIR: temporary directory
BKPDIR: directory to save the back up files
WWWDIR: parent directory that needed to be backed up
BKP: list of directory that will be backed up
NOTBKP: list directory that will not be backed up


#!/bin/bash

DATE=`date`
DAY=`date +%d`
LOG="/var/log/backup/typo3_backup.log"
TEMPDIR="/temp/db"
BKP2="typo3_backup_temp"
BKPDIR="/home/backup/typo3"
BKPFILE="20`date +%y_%m_%d_%j`_typo3_backup.tgz"
WWWDIR="/var/www/"
BKP=('fileadmin' 'uploads' 'typo3conf')
NOTBKP=('fileadmin/bigdata' 'fileadmin/files/movie' 'fileadmin/others/bigdata')

proc_time(){
  SD=`echo -n "$1" | grep real`
  TIME=`echo -n "$SD" | awk '{printf $2}'`
  echo -e "`date` - $2 done [ $TIME ]" 2>&1 | tee -a $LOG
}

if [ "$DAY" == "01" ]; then
  echo "=== Start backup on $DATE ===" 2>&1 | tee $LOG
else
  echo "=== Start backup on $DATE ===" 2>&1 | tee -a $LOG
fi
echo "`date` - delete $BKPDIR/*" 2>&1 | tee -a $LOG
  rm -r $BKPDIR/*
  cd $TEMPDIR

echo "`date` - cleanup $TEMPDIR" 2>&1 | tee -a $LOG
  rm -r $TEMPDIR/*

echo -e "`date` - create $BKP2 " 2>&1 | tee -a $LOG
  mkdir $BKP2

echo "`date` - dump the database" 2>&1 | tee -a $LOG
  SD=$( { time nice -n 15 mysqldump --opt --quick -l -hlocalhost -uDBUSER -pDBPASSWORD typo3_host > $BKP2/db.sql ; } 2>&1 )
  proc_time "$SD" "dump db"

for e in "${NOTBKP[@]}"; do
  EX="`echo -n $EX` --exclude=$e"
done

for b in "${BKP[@]}"; do
  BK="`echo -n $BK` $b"
done

echo "`date` - compressing db & typo3" 2>&1 | tee -a $LOG
SD=$( { time nice -n 15 tar -czvhf $BKPDIR/$BKPFILE -C $WWWDIR $BK $EX -C $TEMPDIR $BKP2 ; } 2>&1 )
proc_time "$SD" "compressing db & typo3"

rm -R $BKP2
chown copyuser:root $BKPDIR/$BKPFILE
chmod 400 $BKPDIR/$BKPFILE
SIZE=`ls -lh $BKPDIR/$BKPFILE | awk '{printf $5}'`
echo "`date` - backup size $SIZE" 2>&1 | tee -a $LOG
echo "=== backup finish ===" 2>&1 | tee -a $LOG

No comments: