Bash Server Backup Script

I’ve created a Bash Server Backup Script that will backup your MySQL databases (each database separately in to .sql and .xml files) and your main directories (/var/log, /var/www/html, /etc, /home, /root) to a timestamped directory. Feel free to re-use or hack up however you’d like

Here’s my Bash Server Backup Script:
Download the script here

#/bin/bash -l
#
# Author: Steve Stonebraker
# Date: 7/19/2012
#
# Script name: backup_server.sh
#
#
# Backup Script purpose, to backup:
# 1. MySQL
# -create .sql and .xml dumps for each database separately
# 2. path's to log, http, etc, home, www
#
# Requirement: User must set values in section below
#
#
# How to use: Place script in cron to run daily

###USER MUST SET FOR SERVER ###
BACKUP_DEST="/root/backups"
MUSER="root"
MPASS="password"
MHOST="localhost"
pathLOG="/var/log"
pathHTTP="/opt/nginx"
pathWWW="/var/www"
pathETC="/etc"
pathHOME="/home"
#################################

DATE="$(which date)"
HOST=$(hostname|cut -f1 -d.)
currtimestamp=$($DATE +%Y-%m-%d--%H-%M-$HOST)
path="$BACKUP_DEST/${currtimestamp}"
oldbackups="$BACKUP_DEST/old"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
BAKMYSQLPATH="$path/mysql"
BAKDIRPATH="$path/directories"
GZIP="$(which gzip)"
TAR="$(which tar)"
CHMOD="$(which chmod)"
MKDIR="$(which mkdir)"
RM="$(which rm)"
ECHO="$(which echo)"
FIND="$(which find)"

#####
##Find backups older than fifteen days, remove them
$MKDIR -p $oldbackups; $FIND $BACKUP_DEST -type d -mtime +15 -exec mv {} $oldbackups/ \;
$RM -Rf $oldbackups
#####

###CREATE BACKUP DIRECTORY IF IT DOESN'T EXIST, REMOVE IF IT DOES ###
[ ! -d $BAKMYSQLPATH ] && $MKDIR -p $BAKMYSQLPATH || $RM -f $BAKMYSQLPATH/*
[ ! -d $BAKDIRPATH ] && $MKDIR -p $BAKDIRPATH || $RM -f $BAKDIRPATH/*
$TAR -czvf $BAKDIRPATH/${currtimestamp}_log.tar.gz $pathLOG/
$TAR -czvf $BAKDIRPATH/${currtimestamp}_http.tar.gz $pathHTTP/
$TAR -czvf $BAKDIRPATH/${currtimestamp}_etc.tar.gz $pathETC/
$TAR -czvf $BAKDIRPATH/${currtimestamp}_home.tar.gz $pathHOME/
$TAR -czvf $BAKDIRPATH/${currtimestamp}_www.tar.gz $pathWWW/

cd $BAKMYSQLPATH

##List all databases
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
$ECHO "Found databases:"
$ECHO $DBS

for db in $DBS
## DUMP each database in .sql and .xml format, compress
do
$MYSQLDUMP -u $MUSER -p$MPASS $db > $BAKMYSQLPATH/$db.sql
$MYSQLDUMP -u $MUSER -p$MPASS $db --xml > $BAKMYSQLPATH/$db.xml

$GZIP -9 $BAKMYSQLPATH/$db.sql
$GZIP -9 $BAKMYSQLPATH/$db.xml
mv $BAKMYSQLPATH/$db.sql.gz $BAKMYSQLPATH/${currtimestamp}_$db.sql.gz
mv $BAKMYSQLPATH/$db.xml.gz $BAKMYSQLPATH/${currtimestamp}_$db.xml.gz
done

#SET PERMISSION SO ONLY USER RUNNING CAN SEE FILES BACKED UP
$CHMOD -R 600 $BACKUP_DEST
$ECHO "DB Backup complete."
$ECHO "Backup files are located in $BAKMYSQLPATH"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.