Friday, April 23, 2010

Simple tar backup script

Here is a simple backup script (/usr/local/sbin/backup):
#!/bin/bash
#
# creates backups of essential files
#

BACKUPDIR=/var/backups
KEEPDAYS=7

DATA="/root /home /srv \
/boot/grub/menu.lst \
--exclude=$BACKUPDIR"

CONFIG="/etc /var /usr/local \
--exclude=/var/cache/apt/archives \
--exclude=/var/cache/man \
--exclude=/var/run \
--exclude=/var/tmp \
--exclude=/var/lock \
--exclude=$BACKUPDIR \
--exclude=*.gz"

#
# implementation details
#

DATE=`date +%Y-%m-%d-%H-%M`
COMPUTER=`hostname`

# Remove files older than KEEPDAYS days
find "$BACKUPDIR/" -name $COMPUTER-*.tgz \
-type f -mtime +$KEEPDAYS -delete

# Backup data

BACKUPFILE="$BACKUPDIR/$COMPUTER-data-$DATE.tgz"
tar cfz $BACKUPFILE $DATA \
--ignore-failed-read 2> /dev/null

chmod o-o $BACKUPFILE
chgrp adm $BACKUPFILE

# Backup configs

BACKUPFILE="$BACKUPDIR/$COMPUTER-config-$DATE.tgz"
tar cfz $BACKUPFILE $CONFIG \
--ignore-failed-read 2> /dev/null

chmod o-o $BACKUPFILE
chgrp adm $BACKUPFILE
Run it by cron per schedule (file /usr/local/sbin/cron-backup):
#
# Regular cron jobs for backup
#
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
HOME=/
LOG=/dev/null

# Every day at 21:15
15 21 * * * root test -x /usr/local/sbin/backup && backup >> $LOG
Let cron know about our scheduled backup:
ln -s /usr/local/sbin/cron-backup /etc/cron.d/cron-backup
The backup files are in $BACKUPDIR (/var/backups):
deby:~# ls -lh /var/backups/
total 38M
-rw-r----- 1 root adm   19M 2010-04-23 23:30 deby-config-2010-04-23-23-30.tgz
-rw-r----- 1 root adm  4.3K 2010-04-23 23:30 deby-data-2010-04-23-23-30.tgz
...

No comments :

Post a Comment