Skip to content

Instantly share code, notes, and snippets.

@holly
Last active December 16, 2015 23:59
Show Gist options
  • Save holly/5517317 to your computer and use it in GitHub Desktop.
Save holly/5517317 to your computer and use it in GitHub Desktop.
dar easy backup
#!/bin/bash
# cron setting example
# 5 3 * * * ionice -c2 -n7 nice -n19 /usr/local/sbin/dar-differential-backup.sh >/dev/null 2>&1
# or
# ALLNICE="ionice -c2 -n7 nice -n19"
# BACKUP_SCRIPT="/usr/local/sbin/dar-differential-backup.sh"
# 5 3 * * 0 $ALLNICE $BACKUP_SCRIPT -f >/dev/null 2>&1
# 5 3 * * 1,2,3,4,5,6 $ALLNICE $BACKUP_SCRIPT -d >/dev/null 2>&1
set -e
set -x
BACKUP_DIR=/backup
DAR=/usr/bin/dar
DAR_ARGS="-R / -w -z -Q"
WEEK_ROTATE=5
if [ -z "$TARGET_DIRS" ]; then
TARGET_DIRS="-g home -g etc -g root -g usr/local"
fi
if [ -z "$DO_NOT_COMPRESSIONS" ]; then
DO_NOT_COMPRESSIONS="-Z *.gz -Z *.png -Z *.jpg -Z *.jpeg -Z *.bz2"
fi
if [ -z "$EXCLUDES" ]; then
EXCLUDES="-X *.swp -X *.tmp -X *.org -X *.pid -X lock -X *~"
fi
day_of_first_in_week(){
date +%Y%m%d --date "$(date +%w) days ago"
}
today(){
date +%Y%m%d
}
full_backup_archive_name(){
local day=$1
if [ -z "$day" ]; then
day=$(day_of_first_in_week)
fi
ls $BACKUP_DIR/$day/*-full*.dar 2>/dev/null | sed -e 's/^\(.*-full\).*$/\1/'
}
rotate_backup_dir(){
local work_dirs=($(ls -1 -d $BACKUP_DIR/* 2>/dev/null | sort -nr))
while [ ${#work_dirs[@]} -gt $WEEK_ROTATE ]; do
local last_index=$((${#work_dirs[@]} - 1))
rm -fr ${work_dirs[$last_index]}
unset work_dirs[$last_index]
done
}
### start ###
work_dir=$BACKUP_DIR/$(day_of_first_in_week)
full_backup_base=$(full_backup_archive_name)
# getopt
while getopts fd OPT; do
case $OPT in
"f" ) type="full"; mkdir -p $work_dir;;
"d" ) type="diff";;
"a" ) type="auto";;
esac
done
if [ -z "$type" ]; then
type="auto"
fi
# make backup directory
if [ "$type" = "auto" ]; then
if [ ! -d $work_dir ]; then
mkdir -p $work_dir
type="full"
else
if [ -z "$full_backup_base" ] ; then
type="full"
else
type="diff"
fi
fi
fi
rotate_backup_dir
archive_base=$work_dir/$(today)-$type
dar_args="$DAR_ARGS $TARGET_DIRS $DO_NOT_COMPRESSIONS $EXCLUDES -c $archive_base"
if [ $type = "diff" ]; then
dar_args="$dar_args -A $full_backup_base"
fi
eval $(echo $DAR $dar_args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment