5333 private links
Q: How to delete all but last [n] ZFS snapshots?
Does anyone have any good ways / scripts they use to manage the number of snapshots stored on their ZFS systems? Ideally, I'd like a script that iterates through all the snapshots for a given ZFS filesystem and deletes all but the last n snapshots for that filesystem.
E.g. I've got two filesystems, one called tank and another called sastank. Snapshots are named with the date on which they were created: sastank@AutoD-2011-12-13 so a simple sort command should list them in order. I'm looking to keep the last 2 week's worth of daily snapshots on tank, but only the last two days worth of snapshots on sastank.
A:
zfs list -t snapshot -o name | grep ^tank@Auto | tac | tail -n +16 | xargs -n 1 zfs destroy -r
- Output the list of the snapshot (names only) with zfs list -t snapshot -o name
- Filter to keep only the ones that match tank@Auto with grep ^tank@Auto
- Reverse the list (previously sorted from oldest to newest) with tac
- Limit output to the 16th oldest result and following with tail -n +16
- Then destroy with xargs -n 1 zfs destroy -vr
Deleting snapshots in reverse order is supposedly more efficient or sort in reverse order of creation.
zfs list -t snapshot -o name -S creation | grep ^tank@Auto | tail -n +16 | xargs -n 1 zfs destroy -vr
A:
More general case of getting most recent snapshot based on creation date, not by name.
zfs list -H -t snapshot -o name -S creation | head -1
Scoped to a specific filesystem name TestOne
zfs list -H -t snapshot -o name -S creation -d1 TestOne | head -1
-H: No header so that first line is a snapshot name
-t snapshot: List snapshots (list can list other things like pools and volumes)
-o name: Display the snapshot name property.
-S creation: Capital S denotes descending sort, based on creation time. This puts most recent snapshot as the first line.
-d1 TestOne: Says include children, which seems confusing but its because as far as this command is concerned, snapshots of TestOne are children. This will NOT list snapshots of volumes within TestOne such as TestOne/SubVol@someSnapshot.
| head -1: Pipe to head and only return first line. //
Thanks for the -d1. That was the key to the question "How do I get all snapshots for a given dataset?"