Archived Mac & OS X Uncategorized

Mounting Time Machine backup inside OS X terminal

Before I started using my Macbook Pro as my only machine a few days ago, I had my iMac in the office and the MBP for portable use.  This was getting painful because of the amount of time I spent keeping the machines in sync so did a complete Time Machine backup of the iMac and don’t use it anymore.

One of the problems, of course, was getting all my data from the Time Machine backup to the Macbook Pro, based on the fact that the MBP’s built-in hard disk is 500GB where the iMac was 1TB – exactly half.  For that reason I had to be very selective about what files I transferred to the notebook.  I transferred all my iTunes media but only transferred videos I’m yet to watch.

The problem

This was all fine but I was often finding that I wanted to re-watch a video I’d already seen through Apple TV but hadn’t restored from the Time Machine backup.  Sure, you can mount a Time Machine backup in Finder and transfer them that way but I wanted to see if I could automate the process from the command line.  Here’s how I did it.

A small script did the trick

In the OS X Terminal application you can run the following script to mount a Time Machine backup and copy a video that’s passed to the script as a parameter into your iTunes movies directory.

The script mounts the sparsebundle file, copies the video then dismounts the Time Machine sparsebundle.  The mount and unmount processes do require sudo privileges so you may get prompted for a password, depending on your system configuration.  Don’t forget to change the file and device names etc so they match yours.


# mount the Time Machine backup
sudo hdiutil attach -readwrite /Volumes/Backup/backup.sparsebundle

# copy the requested video from the backup to the ~/Movies directory
cp "/Volumes/Time Machine Backups/Backups.backupdb/backup/Latest/ HD/Users/me/Music/iTunes/iTunes Media/Movies/$1" "/Users/me/Music/iTunes/iTunes Media/Movies/"

# unmount the Time Machine backup
sudo hdiutil detach /Volumes/Time Machine Backups/

That’s really all there is to it and it all happens with very little effort.  My script is in the PATH variable so it’s just a case of opening the Terminal (using Alfred, of course) and running the script with the video as a parameter.  If everything goes well you’ll see something like this:

Copy movie script
Sample output from above script