Aug 12 2010
Backup a Directory when Modified
I use this script to keep a full local backup of my tftp directory on Linux. It keeps the archive only if some of the files were modified.
It can be used for any directory indeed. There are the files produced:
[root@tftp_server backup]$ ls -l -rw-r----- 1 tftp tftp 124200 May 1 04:04 tftp-20100501.tgz -rw-r----- 1 tftp tftp 2108159 May 13 04:04 tftp-20100513.tgz -rw-r----- 1 tftp tftp 2108165 May 18 04:04 tftp-20100518.tgz -rw-r----- 1 tftp tftp 2108442 May 20 04:04 tftp-20100520.tgz -rw-r----- 1 tftp tftp 2108545 Jun 1 04:04 tftp-20100601.tgz -rw-r----- 1 tftp tftp 126382 Jun 3 04:04 tftp-20100603.tgz -rw-r----- 1 tftp tftp 126426 Aug 5 04:04 tftp-20100805.tgz -rw-r----- 1 tftp tftp 126485 Aug 7 04:04 tftp-20100807.tgz -rw-r----- 1 tftp tftp 126486 Aug 11 04:04 tftp-20100811.tgz
Set the script in a cron job and it’s fully automated
#!/bin/bash
# Change these settings to your needs
dir_to_backup=/tftpboot
# Backup path and file names
backup_dir=/tmp/backup
backup_file=tftp
# Zipped tar output file
of=$backup_dir/$backup_file-$(date +%Y%m%d).tgz
# Backup file owner and groupe owner
owner=tftp
gowner=tftp
tmpfile=/tmp/$backup_file.tar
# Number of backup versions to keep
backup_number=24
# Backup
cd $dir_to_backup
# Split tar and zip commands
# to create identical archives with the same checksum
# if files have not changed
tar cf $tmpfile .
# Archive is removed if checksum identical to last archive
# Do not save files timestamp to keep checksum consistent accross the days
gzip -cn $tmpfile > $of
rm -f $tmpfile
chmod 640 $of
chown $owner:$gowner $of
# Remove new archive if last backup checksum is identical
[ `ls -1t $backup_dir/$backup_file-*.tgz|head -2|xargs md5sum|awk '{print $1}'|uniq|wc -l` -eq 1 ] && rm -f $of
# Remove older versions
# Keep the last 30 files
ls -1rt $backup_dir/$backup_file-*.tgz|head -n -$backup_number|xargs rm -f

