The Code
Let's write
the code. First, we need to name a few things.
SOURCE is the volume we are backing up—in
this case, root. FILEDEST is the volume where the
backup will be stored. All disk images require a
VOLUMENAME; otherwise, they get called
untitled, which is really not a lot of use to
anyone, so we set it to backup_YYYY-MM-DD and use
it as the basis of the IMAGENAME:
#!/bin/sh
############################################
Set some variables
############################################
### The name of the volume we wish to backup
SOURCE='/'
### The volume onto which we are putting the backup
FILEDEST='/Volumes/Overflow'
### Creating the backup disk image file and volume name
VOLUMENAME=backup_`date +%Y-%m-%d`
IMAGENAME=$FILEDEST/$VOLUMENAME.dmg
############################################
#Create the image
############################################
hdiutil create -srcfolder $SOURCE -fs HFS+ \
-format UDRW -volname $VOLUMENAME $IMAGENAME
Scary, isn't it? hdiutil creates
an image file called IMAGENAME on volume
FILEDEST based on SOURCE. In
this case, SOURCE is my root volume, but it could
be a folder such as /Users/peterhickman if I
wanted to back up only my user files. It took only 15 lines,
including comments. This is the power of hdiutil,
and it can do a whole lot more.
By default, this script creates an uncompressed image, but by
removing -format UDRW, the script creates a
compressed image. Compressed sounds good, but a compressed image
backup takes in excess of two hours, whereas an uncompressed image
backup takes 69 minutes, based on backing up a 10 GB root volume on
my Mac. Additionally, mounting the compressed image takes an age
(minutes as opposed to seconds), which reduces the utility of a
backup. If getting the data out of the backup is too much trouble,
you will wonder why you went to all the trouble of creating one.