Created
August 20, 2023 14:18
-
-
Save jpadhye/33b0513551ea19f841dab0a2ae9bd975 to your computer and use it in GitHub Desktop.
Script to delete time machine backups older than 1 year from all backup disks. Needs sudo permissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Calculate the cutoff date (1 year ago) | |
cutoff_date=$(date -v-1y "+%Y-%m-%d-%H%M%S") | |
echo "cutoff_date => $cutoff_date" | |
# find mount points | |
output=$(sudo tmutil destinationinfo) | |
# Initialize an empty array to store mount points | |
mount_points=() | |
# Use awk to extract the lines containing "Mount Point" | |
while IFS= read -r line; do | |
if [[ $line =~ "Mount Point" ]]; then | |
mount_point=$(echo "$line" | awk -F': ' '{print $2}') | |
mount_points+=("$mount_point") | |
fi | |
done <<< "$output" | |
echo "mount_points => ${mount_points[*]}" | |
# Gather backup timestamps for deletion | |
for mount_point in "${mount_points[@]}"; do | |
# Initialize a string to store timestamps | |
backup_timestamps=() | |
# Gather backups from last calendar year excluding the latest | |
backups=$(sudo tmutil listbackups -d "$mount_point" | sort -n) | |
SAVEIFS=$IFS # Save current IFS (Internal Field Separator) | |
IFS=$'\n' # Change IFS to newline char | |
backups=($backups) | |
IFS=$SAVEIFS # Restore original IFSIFS=$'\n' | |
# Iterate through the dates and keep only those on or after the cutoff date | |
for date in "${backups[@]}"; do | |
if [[ $date < $cutoff_date ]]; then | |
backup_timestamps+=("-t $date ") | |
fi | |
done | |
#echo "backup_timestamps => ${backup_timestamps[*]}" | |
# Delete all gathered backups in a single command | |
if [[ -n "$backup_timestamps" ]]; then | |
echo sudo tmutil delete -d "$mount_point" "${backup_timestamps[@]}" | |
sudo tmutil delete -d "$mount_point" "${backup_timestamps[@]}" | |
#echo "Deleted backups with timestamps:$backup_timestamps" | |
else | |
echo "No backups to delete." | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment