Skip to content

Instantly share code, notes, and snippets.

@anon5r
Forked from bendavis78/db_backup.sh
Last active December 14, 2015 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anon5r/5068096 to your computer and use it in GitHub Desktop.
Save anon5r/5068096 to your computer and use it in GitHub Desktop.
#!/bin/bash
# for use with cron, eg:
# 0 3 * * * root /home/www/batch/bin/backup.sh /var/backup/www
if [[ -z "$1" ]]; then
echo "Usage: $0 <PATH>"
exit 1
fi
TARGET_PATH="$1"; shift
DIR="/var/backup/archives/web"
KEEP_DAILY=7
KEEP_WEEKLY=5
KEEP_MONTHLY=12
if [ -f $TARGET_PATH ] || [ -d $TARGET_PATH ]; then
TARGET=`basename $TARGET_PATH`
else
TARGET=$TARGET_PATH
fi
function rotate {
rotation=$1
fdate=`date +%Y-%m-%d -d $date`
file=$DIR/daily/*$fdate*.tar.bz2
mkdir -p $DIR/$rotation/ || abort
if [ -f $file ]; then
cp $file $DIR/$rotation/ || abort
else
echo
fi
}
function prune {
dir=$DIR/$1
keep=$2
target=$3
ls $dir | sort -rn | grep -s " ${target}_" | awk " NR > $keep" | while read f; do rm $dir/$f; done
}
function md5_diff {
dir=$DIR/$1
target=$2
date_new=$3
date_old=$4
if [ ! -f $dir/${target}_${date_old}.tar.bz2 ]; then
return 1
fi
last=`md5sum $dir/${target}_${date_old}.tar.bz2 | awk '{print $1}'`
curr=`md5sum $dir/${target}_${date_new}.tar.bz2 | awk '{print $1}'`
if [ "$last" = "$curr" ]; then
rm $dir/${target}_${date_new}.tar.bz2
fi
}
function abort {
echo "aborting..."
exit 1
}
mkdir -p $DIR/daily || abort
mkdir -p $DIR/weekly || abort
mkdir -p $DIR/monthly || abort
mkdir -p $DIR/yearly || abort
date=`date +%Y-%m-%d` || abort
day=`date -d $date +%d` || abort
weekday=`date -d $date +%w` || abort
month=`date -d $date +%m` || abort
yesterday=`date -d yesterday +%Y-%m-%d` || abort
# Do the daily backup
oldpath=`pwd`
cd `dirname $TARGET_PATH`
tar jcf $DIR/daily/${TARGET}_${date}.tar.bz2 `basename $TARGET_PATH`
test ${PIPESTATUS[0]} -eq 0 || abort
cd $oldpath ; unset $oldpath
# Perform rotations
if [[ "$weekday" == "0" ]]; then
rotate weekly
fi
if [[ "$day" == "01" ]]; then
rotate monthly
fi
if [[ "$month/$day" == "01/01" ]]; then
rotate yearly
fi
md5_diff daily $TARGET $date $yesterday
prune daily $KEEP_DAILY $TARGET
prune weekly $KEEP_WEEKLY $TARGET
prune monthly $KEEP_MONTHLY $TARGET
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment