Aug 12 2010

Backup a Directory when Modified

Published by at 10:03 am under Backup,Linux

I use this script to keep a full local backup of my tftp directory hosted on Linux. It keeps the archive only if some of the files were modified. It lets me restore in a quicker way than using a heavy backup software, which can be used beside to secure the backup elsewhere.
The shell script can be run for any directory indeed. There are the files produced on my TFTP server:

[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 to run once every day.


# Change these settings to your needs
# Backup path and file names
# Zipped tar output file
of=$backup_dir/$backup_file-$(date +%Y%m%d).tgz
# Backup file owner and groupe owner
# Number of backup versions to keep

# 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

Another way would be to retrieve the date of the last backup, search in the directory if some files have been modified since and create the zip file if the condition is true.

The script would need some minor adjustments to run on MacOS on which the checksum command is md5 instead of md5sum. MacOS md5 returns a different output.

No responses yet

Comments RSS

Leave a Reply