Skip to content

Instantly share code, notes, and snippets.

@webercoder
Created July 17, 2013 07:56
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 webercoder/6018608 to your computer and use it in GitHub Desktop.
Save webercoder/6018608 to your computer and use it in GitHub Desktop.
Converting this to a gist and blowing away the repo. Never been used, probably never will be.
#!/bin/bash
# Inspired by http://www.mikerubel.org/computers/rsync_snapshots/
# Command Line Options
PREFIX=$1
COUNT=$2
SOURCE_DIRECTORY=$3
DESTINATION_DIRECTORY=$4
EXCLUDES=$5
# Run checks
if [ $# -lt 4 ]
then
echo ""
echo " Usage: $0 prefix count source-directory destination-directory [rsync-exclusions-file]"
echo " For example: $0 hourly 24 /home/user /var/backup/home/user/hourly"
echo ""
exit 1
elif [ ! -d $SOURCE_DIRECTORY ]
then
echo "$SOURCE_DIRECTORY (source directory) does not exist."
exit 2
elif [ ! -d $DESTINATION_DIRECTORY ]
then
echo "$DESTINATION_DIRECTORY (destination directory) does not exist."
exit 3
fi
# Delete the oldest snapshot
if [ -d $DESTINATION_DIRECTORY/$PREFIX.$COUNT ]
then
echo "Removing $PREFIX.$COUNT"
rm -rf $DESTINATION_DIRECTORY/$PREFIX.$COUNT
else
echo "Not removing $PREFIX.$COUNT because it doesn't exist."
fi
# Shift the middle snapshots(s) back by one
for ((current=$COUNT; current>2; current--))
do
previous=$(($current-1))
if [ -d $DESTINATION_DIRECTORY/$PREFIX.$previous ]
then
echo "Moving $PREFIX.$previous to $PREFIX.$current"
mv $DESTINATION_DIRECTORY/$PREFIX.$previous $DESTINATION_DIRECTORY/$PREFIX.$current
else
echo "Not moving $PREFIX.$previous because it does not exist"
fi
done
# Make a hard-link-only (except for dirs) copy of the latest snapshot
# Otherwise, make $PREFIX.1
if [ -d $DESTINATION_DIRECTORY/$PREFIX.1 ]
then
echo "Copying (-al) $PREFIX.1 to $PREFIX.2"
cp -al $DESTINATION_DIRECTORY/$PREFIX.1 $DESTINATION_DIRECTORY/$PREFIX.2
else
echo "Creating $DESTINATION_DIRECTORY/$PREFIX.1"
mkdir $DESTINATION_DIRECTORY/$PREFIX.1
fi
# Create latest snapshot
echo "Running rsync on $SOURCE_DIRECTORY to $DESTINATION_DIRECTORY/$PREFIX.1"
if [ -f $EXCLUDES ]
then
rsync -a --delete --delete-excluded --exclude-from="$EXCLUDES" $SOURCE_DIRECTORY $DESTINATION_DIRECTORY/$PREFIX.1
else
rsync -a --delete --delete-excluded $SOURCE_DIRECTORY $DESTINATION_DIRECTORY/$PREFIX.1
fi
# Update the mtime of current snapshot
echo "Updating date of $PREFIX.1"
touch $DESTINATION_DIRECTORY/$PREFIX.1
echo "Script complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment