10.5: A script to fix Time Machine after hardware repairs

Dec 19, '08 07:30:04AM

Contributed by: Anonymous

Apparently I have bad luck with MacBooks, because I have found myself going through this Time Machine repair guide with shocking frequency. The process of migrating an old Time Machine backup to a new machine is pretty involved and prone to errors, so I wrote a shell script that gets the job done automatically:

#!/bin/bash
if [[ "$USER" != "root" ]]; then
  echo "You must run this script as root."
  exit 1
fi

VOLUME=`find /Volumes -mindepth 1 -maxdepth 2 -name 'Backups.backupdb' | head -n1 | sed 's/\/Backups.backupdb$//'`
if [[ -z "$VOLUME" ]]; then
  echo "Could not find a Time Machine drive. Please connect a drive and try again."
  exit 1
fi

BACKUP=`ls -d "$VOLUME/Backups.backupdb/"* | head -n1`
if [[ -z "$BACKUP" ]]; then
  echo "Could not find a Time Machine backup on the volume."
  exit 1
fi

OLDMAC=`xattr -p com.apple.backupd.BackupMachineAddress "$BACKUP"`
if [[ -z "$OLDMAC" ]]; then
  echo "Could not discover old MAC."
  exit 1
fi

NEWMAC=`ifconfig en0 | egrep -o 'ether ([0-9a-f]{2}:){5}[0-9a-f]{2}' | cut -c7-`
if [[ -z "$NEWMAC" ]]; then
  echo "Could not discover new MAC."
  exit 1
fi
if [[ "$NEWMAC" = "$OLDMAC" ]]; then
  echo "Found a Time Machine backup, but it's already bound to this machine."
  exit 1
fi

echo "Discovered a Time Machine backup at $BACKUP for MAC: $OLDMAC. Your new MAC is: $NEWMAC."
echo "Press enter to bind this backup to this machine, or Ctrl+C to cancel."
read

fsaclctl -p "$VOLUME" -d && \
mv "$VOLUME/.`echo "$OLDMAC" | sed s/://g`" "$VOLUME/.`echo "$NEWMAC" | sed s/://g`" && \
xattr -w com.apple.backupd.BackupMachineAddress "$NEWMAC" "$BACKUP" && \
OK=1
fsaclctl -p "$VOLUME" -e

if [[ -z "$OK" ]]; then
  echo "Something terrible happened while restoring the backup."
  echo "You're probably worse off now than you were before."
  echo "Sorry. :("
  exit 1
fi

echo "Time Machine backup successfully rebound to this machine. Please eject and reconnect the volume."
echo "Your first Time Machine backup after the restore process may take a really really long time."
echo "Like it might take a day or something, seriously."

It's simple to use:
  1. Copy and paste the entire script to a text file on your Desktop.
  2. Open a terminal, type sudo sh, then press the Space Bar, but do not press Enter/Return yet.
  3. Drag the text file where you saved the script into your Terminal, and then press Enter/Return.
This script will ask you for your password, and then if it discovers an old Time Machine backup, it will ask you if you want to automatically restore it.

[robg adds: I haven't tested this one.]

Comments (24)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20081216145458979