My Backup Script on OS X


It's sysadmin script day on Technometria. Earlier, I posted and explained by script for cleaning up unwanted files in Linux. Later this afternoon Kelly Flanagan asked me how I did backups, so I decided to clean up my backup script and post it for all to see.

First, let me explain that my goal here is to produce a copy of my files. I'm not trying to do imcrementals. This protects me from disk failure, but not my own stupidity. I used to use Synchronize! Pro for backups. It had a few really nice advantages. First if created an image and second, it only copied the files that had changed. But it got flaky and would hang, complain about "non-deletable" files and so on. Those problems, combined with the fact that it's expensive, made me look for another solution.

I started using rsync several months ago to back up my wife's photos. rsync has been around for years and was actually the result of someone's dissertation research in the 80's, if I remember right. I used to use it as a grad student in the 80's to backup my files form one machine to another. It works across a network, if necessary, and also only copies what's changed. In fact, I wouldn't be surprised to find out that Synchronize! Pro was just a fancy front end for rsync.

This script takes a user name as a parameter, and backs up that user to a drive using rsync. The script automatically mounts and unmounts the drive because I hate having the drive spin up every time I go to open or save a file.

#!/bin/bash

USER=$1

echo "Backing up ${USER}"

# backup volume
VOLUME='/Volumes/PantherBackup'

# Get device using  'diskutil info ${VOLUME}'
DEVICE='/dev/disk1s3'

if [ ! -e ${VOLUME} ]
then 
   echo "Mounting ${DEVICE} as ${VOLUME}"
   /usr/sbin/diskutil mount ${DEVICE}
else
   echo "${VOLUME} already mounted"
fi

SRC="/Users/${USER}/"
DEST="${VOLUME}${SRC}"

echo "Backing up " ${SRC} " to " ${DEST}

sudo rsync -av --timeout=120 --delete ${SRC} ${DEST}

echo "Unmounting ${VOLUME}"
/usr/sbin/diskutil eject ${VOLUME}

The script is intentionally chatty and OS X specific. For example, the disk mounting and unmounting uses the OS X diskutil command. To mount the device, you need the device name. You can get that with diskutil (or it's graphical sibling DiskUtil) by asking for the "info" on the volume when it's mounted.

Note that I run rsync as root since there are some root owned files in my directory space (from CPAN). I modified the /etc/sudoers file (with visudo) so that I can run rsync as root without a password. Be careful if you do this. It's easy to make a mistake in the sudoer syntax and make it so you can't use sudo anymore.


Please leave comments using the Hypothes.is sidebar.

Last modified: Thu Oct 10 12:47:19 2019.