Skip to content

Instantly share code, notes, and snippets.

@vittorioromeo
Last active December 19, 2015 06:09
Show Gist options
  • Save vittorioromeo/5909350 to your computer and use it in GitHub Desktop.
Save vittorioromeo/5909350 to your computer and use it in GitHub Desktop.
This script backups the whole filesystem. It stores the last 15 backup folders in a text file, '_LAST', and rotates the backups by deleting the fifteenth folder (and text line).
#!/bin/bash
# Set directories
BACKUPDIR="/media/veeBackup/_ARCHBACKUP/"
TEMPDIR="${BACKUPDIR}_TEMP/"
TEMPFILE="${TEMPDIR}tmpfile"
LASTENTRIESFILE="${BACKUPDIR}_LAST"
# Get all entries from LASTENTRIESFILE (one entry per line) and put them in the LASTENTRIES array
OLD_IFS=$IFS
IFS=$'\n'
LASTENTRIES=($(cat $LASTENTRIESFILE)) # array
IFS=$OLD_IFS
# Set backup name (NEW is the name of the new backup folder) (LASTENTRY is the name of the old backup folder)
NEW=`date -Iseconds`
LASTENTRY=${LASTENTRIES[0]}
# Set rsync options
SRC="/*"
TRG="${BACKUPDIR}${NEW}"
LNK="${BACKUPDIR}${LASTENTRY}"
OPT="-aAXv --delete --link-dest=$LNK"
# Run rsync!
rsync $OPT $SRC $TRG --exclude={/dev/*,/proc/*,/sys/*,/tmp/*,/run/*,/mnt/*,/media/*,/lost+found,/home/stuff,/var/tmp,/var/log,"/home/vittorioromeo/VirtualBox VMs",/home/.cache,/home/vittorioromeo/.cache}
# Prepend the NEW folder name to the _LAST file
echo $NEW | cat - "${LASTENTRIESFILE}" > "${TEMPFILE}" && mv "${TEMPFILE}" "${LASTENTRIESFILE}"
# Count LASTENTRIES
NUMLASTENTRIES=${#LASTENTRIES[@]}
# If there are more than 24 LASTENTRIES, and the 24th LASTENTRY is not empty, remove it and remove the backup folder with its name
if [[ ${NUMLASTENTRIES} > 24 ]]; then
if [[ -z "${LASTENTRIES[24]}" ]]; then
exit 0;
fi
rm -R "${BACKUPDIR}${LASTENTRIES[24]}/"
head -n -1 $LASTENTRIESFILE > "${TEMPFILE}"; mv "${TEMPFILE}" "${LASTENTRIESFILE}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment