How to delete (tmutil delete) all old backups from TimeMachine - keep only current full backup

Solution 1:

As of macOS Big Sur 11.2.3+ - and according to the updated man tmutil - you need to provide the mount point disk and the timestamp of each backup using -d and -t flags, respectively. So the following tweak is needed for the accepted answer:

# assuming you have the backup disk connected & root privileges:
# get the latest backup to exclude from deletion
latest=$(sudo tmutil latestbackup)
# the 4th line after the last space from `tmutil destinationinfo` output
# contains the mount disk name
mountpoint=$(tmutil destinationinfo | sed '4q;d' | sed 's/.* //')
echo "latest is $latest"
# delete all the backups excluding the latest
backups=$(sudo tmutil listbackups)
echo $backups | while read timestamp; do
    if [[ "$timestamp" != "$(basename $latest)" ]]; then
        echo sudo tmutil delete -d $mountpoint -t $timestamp
    fi
done

# if you want to keep the last, say, 3 backups, pipe "sed '$d'" 3-1=2 times:
backups=$(sudo tmutil listbackups | sed '$d' | sed '$d')

It should look like sudo tmutil delete -d /Volumes/TimeMachineBackups -t 2021-04-10-004103.

Solution 2:

#!/bin/bash
latest=$(sudo tmutil latestbackup)
sudo tmutil listbackups | while read backup; do
    if [[ "$backup" != "$latest" ]]; then
        echo sudo tmutil delete "$backup"
    fi
done

Remove the echo once you are sure that the output is correct.