Skip to content

Instantly share code, notes, and snippets.

@sohsatoh
Last active December 21, 2021 13:10
Show Gist options
  • Save sohsatoh/7f8880b39b86de880f59bc1f8b60d9c9 to your computer and use it in GitHub Desktop.
Save sohsatoh/7f8880b39b86de880f59bc1f8b60d9c9 to your computer and use it in GitHub Desktop.
An interactive script to delete time machine backup(s) selectively
#!/usr/bin/env python3
from pick import Picker
import subprocess
# Install pick first ("pip install pick")
print("Retrieving the backup destination...")
dest = subprocess.check_output("sudo tmutil machinedirectory", shell=True).decode("utf-8")
print("Retrieving the backup list...")
backups = []
res = subprocess.check_output("sudo tmutil listbackups", shell=True)
for line in res.decode("utf-8").split("\n"):
if len(line):
backups.append(line.replace(".backup", ""))
# Select backup(s) to delete
def select_all(picker):
return [(l, 0) for l in backups]
title = "Select backup(s) you want to delete (press '→' to select, 'a' to select all): "
picker = Picker(backups, title, multiselect=True, min_selection_count=1)
picker.register_custom_handler(ord('a'), select_all)
selected = picker.start()
print(
"Destination: ", dest, "\n"
"Selected Backup(s): ", selected, "\n"
)
ans = input("Are you sure to delete these backups? ('Y' to Continue): ")
if ans in ["y", "Y"]:
print("Removing selected backup(s)")
for i in range(len(selected)):
print('Deleting {}...'.format(selected[i][0]))
subprocess.run("sudo tmutil delete -d {} -t {}".format(dest, selected[i][0]), shell=True)
else:
print("Canceled.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment