Skip to content

Instantly share code, notes, and snippets.

@adam-vessey
Last active October 8, 2019 19:18
Show Gist options
  • Save adam-vessey/3509d76f7c13451bac328c816269ee1a to your computer and use it in GitHub Desktop.
Save adam-vessey/3509d76f7c13451bac328c816269ee1a to your computer and use it in GitHub Desktop.
MacOS Time Machine helper
#!/bin/sh
# Check for a backup today, if none then mount the Time Machine volume
# and wait for Time Machine to run. When the backup is over, unmount
# the Time Machine volume and exit.
# Set these variables or else
# for TMVOLUME ls -l /Volumes/ and paste the entire path including spaces in the
# quotes replace 'backup drive' below, TMFREQ is how recently you care to look
# for a backup
set -x
TMVOLUME=${1:?The name of the backup drive must be provided!}
TMFREQ=${2:-12h}
DISKUTIL=/usr/sbin/diskutil
LOCKFILE="/tmp/$(basename $0).lock"
TMUUID="$($DISKUTIL info "$TMVOLUME" | grep 'Volume UUID' | cut -f 2 -d ':'| awk '{$1=$1};1')"
function check_log() {
log show --style syslog --predicate 'senderImagePath contains[cd] "TimeMachine" AND eventMessage contains[cd] "Backup completed successfully"' --info --last $TMFREQ| grep -v 'Filtering\|Timestamp'
}
function do_mount() {
# See if the Time Machine volume is mounted
# and if it isn't, mount it.
while ! test_dir; do
$DISKUTIL mountDisk "$TMUUID"
if test_dir; then
echo "Mounted..."
break
else
echo "Failed to mount? Will try again in 10 seconds."
sleep 10
fi
done
}
function test_dir() {
local DIR="/Volumes/$TMVOLUME"
test -d "$DIR"
local RESULT=$?
if [ $RESULT == "0" ]; then
echo "$DIR exists."
else
echo "$DIR doesn't exist."
fi
return $RESULT
}
function do_unmount() {
# Unmount the Time Machine volume and exit
while test_dir; do
$DISKUTIL unmountDisk "$TMUUID"
if test_dir; then
echo "Unmounted..."
break
else
echo "Failed to unmount? Will try again in 10 seconds."
sleep 10
fi
done
}
function mount_backup_and_unmount() {
if ! check_log; then
# No backup yet today.
do_mount
# Wait a while for Time Machine to wake up and do a backup
while ! check_log; do
sleep 300
done
fi
# Backup completed (or none necessary), unmount the Time Machine volume if
# mounted and exit
do_unmount
}
if shlock -d -f $LOCKFILE -p $$; then
mount_backup_and_unmount
rm $LOCKFILE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment