Last Updated: February 25, 2016
·
4.2K
· mathieuruellan

A simple incremental backup on linux with dar

Every day, an incremental backup script runs on my linux machine and stores important files:

  • .bashrc
  • .vimrc
  • .ssh
  • .config
  • etc.

dar is a great tool to make simple incremental backup scripts.

Backup files are stored on a server share, mounted with automount and cifs.

  • create a .backup in your home and fill the array and the target path.
  • run the backup with cron (crontab -e)

code

#!/bin/bash
#====================================================================================
# author: Mathieu Ruellan 
# description: do a full or incremental backup of my environment every day with dar.
#
# ensure you have a $HOME/.backup file like this
# 
##### $HOME/.backup template ######
# # array of files or directories to backup
# # do not put "/" at the beginning of each path!!!
# declare -a FILES_TO_BACKUP=(
#    "home/mathieur/path1" \
#    "home/mathieur/path2" \
#    )
#
# # backup directory
# BACKUP_PATH=/mybackupdirectory (with automount)
#
##################################
#
#====================================================================================


[ -f "${HOME}/.backup" ] || { echo "${HOME}/.backup file not found" ; exit 1 ; }

source ${HOME}/.backup

#do a full backup every 100 days. Otherwise do an incremental backup
MODULO=100

# compresss format extensions: don't need to be compressed 
NO_COMPRESSION_OPTIONS='-an -Z "*.gz" -Z "*.bz2" -Z "*.zip" -Z "*.png" -Z "*.jpg" -Z "*.jpeg" -Z "*.avi" -Z "*.mpg" -Z "*.mpeg" -Z "*.mp3" -Z "*.ogg"  -Z "*.rar" -Z "*.zoo" -Z "*.arj" -Z "*.flac" -Z "*.mkv" -Z "*.3gp" -Z "*.mp4" '

DAR_OPTIONS=" -R / -Q -v -w -z -s 1G -q"

command -v dar >/dev/null 2>&1 || { echo >&2 "dar required but it's not installed.  Aborting."; exit 1; }
command -v ionice >/dev/null 2>&1 || { echo >&2 "ionice required but it's not installed.  Aborting."; exit 1; }

DATE=$(date +"%Y-%j")
CATALOG_FILE=${BACKUP_PATH}catalog
DAY_YEAR=`date +%j`                     # day Number e.g 37
MODULO_MONTH=$(expr  \( ${DAY_YEAR} - 1 \) % ${MODULO} ) 


doFullBackup=0
[ "$MODULO_MONTH" -eq 0 ] && doFullBackup=1
[ ! -f "${CATALOG_FILE}.1.dar" ] && doFullBackup=1

for F in ${FILES_TO_BACKUP[@]} ; do
   OPTIONS=" $OPTIONS -g ${F} "
done

OPTIONS=" $OPTIONS $NO_COMPRESSION_OPTIONS $DAR_OPTIONS "


if [ $doFullBackup = 1 ] ; then
        TARGET="${BACKUP_PATH}FULL.${DATE}"
        echo "+ Doing Dar full Backup $TARGET !!!"
        ionice -c 3 dar -c $TARGET $OPTIONS || { echo >&2 "dar failure"; exit 1; }
else 
        echo "+ Doing Dar Diff Backup $TARGET!!!"
        TARGET="${BACKUP_PATH}DIFF.${DATE}"
        ionice -c 3 dar -c $TARGET -A $CATALOG_FILE $OPTIONS || { echo >&2 "dar failure"; exit 1; }
fi

[ -f "${CATALOG_FILE}.1.dar" ] && rm -rf ${CATALOG_FILE}.*

dar -C "${CATALOG_FILE}" -A $TARGET || { echo >&2 "catalog built failure"; exit 1; }