Skip to content

Instantly share code, notes, and snippets.

@johncarl81
Last active October 11, 2015 21:38
Show Gist options
  • Save johncarl81/3923572 to your computer and use it in GitHub Desktop.
Save johncarl81/3923572 to your computer and use it in GitHub Desktop.
Rotating Backups
#!/bin/bash
unset PATH;
# $1 = path to backup
# $2 = name of backup folder
# ------------- system commands used by this script --------------------
ID=/usr/bin/id;
ECHO=/bin/echo;
MOUNT=/bin/mount;
RM=/bin/rm;
MV=/bin/mv;
CP=/bin/cp;
TOUCH=/bin/touch;
RSYNC=/usr/bin/rsync;
# ------------- file locations -----------------------------------------
MOUNT_DEVICE=/dev/sdc1;
SNAPSHOT_RW=/mnt/back1;
EXCLUDES=/root/backup_excludes.txt;
BACKUP_COUNT=100;
BACKUP_NAME=backup;
# ------------- the script itself --------------------------------------
# make sure we're running as root
if (( `$ID -u` != 0 )); then
$ECHO "Sorry, must be root. Exiting..."; exit;
fi
# attempt to remount the RW mount point as RW; else abort
$MOUNT -o remount,rw $MOUNT_DEVICE $SNAPSHOT_RW ;
if (( $? )); then
$ECHO "snapshot: could not remount $SNAPSHOT_RW readwrite";
exit;
fi;
# step 1: delete the oldest snapshot, if it exists:
if [ -d $SNAPSHOT_RW/$2/$BACKUP_NAME.$BACKUP_COUNT ] ; then
$RM -rf $SNAPSHOT_RW/$2/$BACKUP_NAME.$BACKUP_COUNT ;
fi ;
# step 2: shift the middle snapshots(s) back by one, if they exist
for (( i = $BACKUP_COUNT; i >= 1 ; i-- ))
do
if [ -d $SNAPSHOT_RW/$2/$BACKUP_NAME.$(($i-1)) ] ; then
$MV $SNAPSHOT_RW/$2/$BACKUP_NAME.$(($i-1)) $SNAPSHOT_RW/$2/$BACKUP_NAME.$i;
fi;
done
# step 3: rsync from the system into the latest snapshot (notice that
# rsync behaves like cp --remove-destination by default, so the destination
# is unlinked first. If it were not so, this would copy over the other
# snapshot(s) too!
$RSYNC -va --delete --delete-excluded --exclude-from="$EXCLUDES" --link-dest=$SNAPSHOT_RW/$2/$BACKUP_NAME.1 $1 $SNAPSHOT_RW/$2/$BACKUP_NAME.0;
# step 4: update the mtime of $BACKUP_NAME.0 to reflect the snapshot time
$TOUCH $SNAPSHOT_RW/$2/$BACKUP_NAME.0 ;
# now remount the RW snapshot mountpoint as readonly
$MOUNT -o remount,ro $MOUNT_DEVICE $SNAPSHOT_RW ;
if (( $? )); then
$ECHO "snapshot: could not remount $SNAPSHOT_RW readonly";
exit;
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment