server backup script

My Server creates daily backups incremental backups to monthly full backups. It will keep the last three daily backups, as well as the last three monthly backups.

#!/bin/bash

# mru, feb 2010

# make backups.
#


DATE_D=$(date "+%Y%m%d")
DATE_M=$(date "+%Y%m")

BACKUPS=/var/backups
TARGET_D=${BACKUPS}/daily_backup_${DATE_D}.tar.gz
TARGET_M=${BACKUPS}/monthly_backup_${DATE_M}.tar.gz
RECEIVER=mru
TAROPTS=" --preserve-permission --label=$DATE_D"

FILES='
root
home
etc
boot
var/trac
var/www
var/mail
var/repositories
'

EXCLUDE_CLAUSE="
--exclude *~
--exclude ${BACKUPS}
--exclude root/.cpan
--exclude root/caldav
--exclude root/tmp
"

trap '{
 echo \"Failed. Stopping.\";
 exit 1;
 if [ -f "$TARGET" ]; then
   rm $TARGET;
 fi
}' ERR

# remove old files

OLD_D=$(find $BACKUPS -name daily_backup_????????.tar.gz | sort -n | head -n -3)
OLD_M=$(find $BACKUPS -name monthly_backup_??????.tar.gz | sort -n | head -n -3)
OLD=${OLD_M}${OLD_D}
echo "$OLD" | xargs --no-run-if-empty rm

# make monthly spinoff

if [ -f $TARGET_M ]; then
    TAROPTS+=" --newer $TARGET_M"
    TARGET=$TARGET_D
else
    TARGET=$TARGET_M
fi


# create archive
# chdir to / to get the right globbing
( cd / && tar czf "$TARGET" $TAROPTS $EXCLUDE_CLAUSE $FILES )


chmod og-r "$TARGET"

# send report

mail -s "Backup Message for ${HOSTNAME} $(date)" ${RECEIVER} <<EOF
Backup created.

Filename: $TARGET
size:     $(ls -lah $TARGET)

$(if [ -n "$OLD" ]; then echo "==== removed these files: $OLD"; fi)

==== archive content $TARGET:
$(tar tzf $TARGET)

==== folder content $BACKUPS:
$(find ${BACKUPS})
EOF

0 Kommentare:

Kommentar veröffentlichen