Skip to content

Instantly share code, notes, and snippets.

@linjer
Last active April 1, 2024 07:15
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save linjer/a2da823718de9ba28373 to your computer and use it in GitHub Desktop.
Save linjer/a2da823718de9ba28373 to your computer and use it in GitHub Desktop.
Script to automatically remote old Mac OSX Time Machine Backups older than a specified number of days

Prerequisites

  • gfind (via brew install findutils)
  • Time Machine drive mounted on your computer (or you can change path from standard /Volume/Time\ Machine\ Backups/Backups.backup.db/
  • Admin/sudo access in the OSX terminal

Script

  • Be sure to set the correct machine name. You can check the actual folder things are going into by looking in the backup location.
  • By default, it erases all backups older than 30 days. Adjust as desired.

Usage

$ sudo ./tmcleanup.sh
*-* Removing old Time Machine Backups for vitruvius older than 30 days *-*
Deleting: /Volumes/Time Machine Backups/Backups.backupdb/vitruvius/2014-07-21-231955
Deleted (29.7G): /Volumes/Time Machine Backups/Backups.backupdb/vitruvius/2014-07-21-231955
Total deleted: 29.7G
Elapsed time: 2768 secs.
Finished!
#!/bin/bash
#
# Pre-requesite is that GNU linux findutils package is installed (brew install findutils) for gfind
# Should be possible to just use find but I have not tested it (should just omit -daystart)
#
BACKUP_LOCATION=/Volumes/Time\ Machine\ Backups/Backups.backupdb/
MACHINE_NAME=vitruvius
DAY_AGE=30
if [ ! -d "${BACKUP_LOCATION}" ]; then
echo "${BACKUP_LOCATION} is currently not accessible. Please connect your Time Machine disk or change the path."
exit
fi
echo "*-* Removing old Time Machine Backups for ${MACHINE_NAME} older than ${DAY_AGE} days *-*"
# Get a list of all the
result=$(gfind "${BACKUP_LOCATION}""${MACHINE_NAME}"/ -daystart -maxdepth 1 -mindepth 1 -mmin +$((60*24*${DAY_AGE})))
echo "$result"
if [ -n "$result" ]; then
while read -r line; do
START_TIME=$(date +%s)
tmutil delete "$line"
END_TIME=$(date +%s)
echo "Elapsed time: $(($END_TIME - $START_TIME)) secs."
done <<< "$result"
echo "Finished!"
else
echo "Did not find any Time Machine Backups older than ${DAY_AGE} days old."
fi
@septs
Copy link

septs commented Feb 17, 2021

$ tmutil machinedirectory
/Volumes/Time Machine Backups/Backups.backupdb/CBDesktop02

use tmutil machinedirectory command can simplify logic

@brunocbr
Copy link

brunocbr commented Aug 1, 2021

To use BSD find without the need to install anything:

STARTDATE=$(date -v -${DAY_AGE}d +%Y-%m-%d)
result=$(find "${BACKUP_LOCATION}""${MACHINE_NAME}"/ -maxdepth 1 -mindepth 1 -not -newermt "${STARTDATE}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment