Incremental Backup Scripts

#!/bin/bash
2# ----------------------------------------------------------------------
3# mikes handy rotating-filesystem-snapshot utility
4# ----------------------------------------------------------------------
5# this needs to be a lot more general, but the basic idea is it makes
6# rotating backup-snapshots of /home whenever called
7# ----------------------------------------------------------------------
8 
9unset PATH  # suggestion from H. Milz: avoid accidental use of $PATH
10 
11# ------------- system commands used by this script --------------------
12ID=/usr/bin/id;
13ECHO=/bin/echo;
14 
15MOUNT=/bin/mount;
16RM=/bin/rm;
17MV=/bin/mv;
18CP=/bin/cp;
19TOUCH=/bin/touch;
20 
21RSYNC=/usr/bin/rsync;
22 
23 
24# ------------- file locations -----------------------------------------
25 
26MOUNT_DEVICE=/dev/hdb1;
27SNAPSHOT_RW=/root/snapshot;
28EXCLUDES=/usr/local/etc/backup_exclude;
29 
30 
31# ------------- the script itself --------------------------------------
32 
33# make sure we're running as root
34if (( `$ID -u` != 0 )); then { $ECHO "Sorry, must be root.  Exiting..."; exit; } fi
35 
36# attempt to remount the RW mount point as RW; else abort
37$MOUNT -o remount,rw $MOUNT_DEVICE $SNAPSHOT_RW ;
38if (( $? )); then
39{
40    $ECHO "snapshot: could not remount $SNAPSHOT_RW readwrite";
41    exit;
42}
43fi;
44 
45 
46# rotating snapshots of /home (fixme: this should be more general)
47 
48# step 1: delete the oldest snapshot, if it exists:
49if [ -d $SNAPSHOT_RW/home/hourly.3 ] ; then        
50$RM -rf $SNAPSHOT_RW/home/hourly.3 ;               
51fi ;
52 
53# step 2: shift the middle snapshots(s) back by one, if they exist
54if [ -d $SNAPSHOT_RW/home/hourly.2 ] ; then        
55$MV $SNAPSHOT_RW/home/hourly.2 $SNAPSHOT_RW/home/hourly.3 ;
56fi;
57if [ -d $SNAPSHOT_RW/home/hourly.1 ] ; then        
58$MV $SNAPSHOT_RW/home/hourly.1 $SNAPSHOT_RW/home/hourly.2 ;
59fi;
60 
61# step 3: make a hard-link-only (except for dirs) copy of the latest snapshot,
62# if that exists
63if [ -d $SNAPSHOT_RW/home/hourly.0 ] ; then        
64$CP -al $SNAPSHOT_RW/home/hourly.0 $SNAPSHOT_RW/home/hourly.1 ;
65fi;
66 
67# step 4: rsync from the system into the latest snapshot (notice that
68# rsync behaves like cp --remove-destination by default, so the destination
69# is unlinked first.  If it were not so, this would copy over the other
70# snapshot(s) too!
71$RSYNC                             
72    -va --delete --delete-excluded             
73    --exclude-from="$EXCLUDES"             
74    /home/ $SNAPSHOT_RW/home/hourly.0 ;
75 
76# step 5: update the mtime of hourly.0 to reflect the snapshot time
77$TOUCH $SNAPSHOT_RW/home/hourly.0 ;
78 
79# and thats it for home.
80 
81# now remount the RW snapshot mountpoint as readonly
82 
83$MOUNT -o remount,ro $MOUNT_DEVICE $SNAPSHOT_RW ;
84if (( $? )); then
85{
86    $ECHO "snapshot: could not remount $SNAPSHOT_RW readonly";
87    exit;

88} fi;