Skip to content

Instantly share code, notes, and snippets.

@duboisph
Created March 11, 2018 21:48
Show Gist options
  • Save duboisph/c946a9ec76fa8ba28668ed7f91ceffb3 to your computer and use it in GitHub Desktop.
Save duboisph/c946a9ec76fa8ba28668ed7f91ceffb3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
VERSION='2.0'
DESC='Rotating incremental backup'
#set -o errtrace
set -o errexit
#-- VARS --#
# Extra rsync options
OPTS='--exclude "lost+found"'
#-- FUNCTIONS --#
# Version & usage info
version() { echo "`basename $0` $VERSION - $DESC"; }
usage() {
version
echo "
Usage:
`basename $0` source destination [rotation]
Arguments:
source - The source directory to backup.
destination - The destination where to place the backup.
rotation - How many backups to rotate. Defaults to 3.
"
}
# Error handling
log() { $* >> $LOG 2>&1; return $?; }
fail() { echo "*** ERROR: $* ***"; exit 1; }
fail_usage() { echo -e "*** ERROR: $* ***\n"; usage; exit 1; }
try() { log $* || fail "Please check $LOG!"; }
#-- CHECKS --#
# Make sure we're running as root
[[ "`id -u`" == '0' ]] || fail "Please run this script as root!"
# Make sure $SRCDIR exists
[[ -n "$1" ]] && SRCDIR="$1" || {
fail_usage "Please specify the source to synchronise!"
}
[[ -d "$SRCDIR" ]] || fail "Source $SRCDIR does not exist!"
# Make sure $DESDIR exists
[[ -n "$2" ]] && DESDIR="$2" || {
fail_usage "Please specify the destination!"
}
[[ -d "$DESDIR" ]] || fail "Destination $DESDIR does not exist!"
# How many backups to rotate
[[ -n "$3" ]] && ROTATE="$3" || ROTATE=3
[[ "$ROTATE" -gt 1 ]] || fail "Rotation must be greater than 1!"
# Set the $TMPDIR
[[ -n "$TMPDIR" ]] || TMPDIR='/tmp'
[[ -d "$TMPDIR" ]] || fail "Temporary dir $TMPDIR does not exist!"
# Name of the logfile
LOG="$TMPDIR/`basename $0`.log"
#-- SCRIPT --#
rm -f $LOG
echo "----------------------- Backup -----------------------"
NAME=`echo "$SRCDIR" | sed 's/\///g'`
NEWESTBAK=`ls -1 $DESDIR | grep backup_$NAME | tail -1`
CURRENTBAK="backup_${NAME}_`date +%Y%m%d%H%M%S`"
# Create hardlinks from $NEWESTBAK to $CURRENTBAK
if [ ! -z $NEWESTBAK ]; then
echo " > Creating hardlinks..."
try cp -al $DESDIR/$NEWESTBAK $DESDIR/$CURRENTBAK
fi
# Do the actual synchronisation
echo " > Synchronizing newest data..."
try rsync -a --delete $OPTS $SRCDIR/ $DESDIR/$CURRENTBAK/
# Remove old backups
NUMBAK=`ls -1 $DESDIR | grep -c backup_$NAME`
if [ "$NUMBAK" -gt "$ROTATE" ]; then
echo " > Removing old backups..."
NUMREM=$[$NUMBAK-$ROTATE]
cd $DESDIR
for BAK in `ls -1 | grep backup_$NAME | head -$NUMREM`; do
rm -rf $BAK
done
fi
echo "----------------------- Done -----------------------"
rm -f $LOG && exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment