Guide: Cleaning up ZFS-Snapshots

Starting a guide-section for problems i encountered. For me to remember and for others to find.

When using a automated backup mechanism for ZFS-snapshots it can get a) very messy and b) when moving lots of files crowed in terms of diskspace.

One solution is to delete some of them. Let’s assume you do not need any of them anymore there are various ways to get rid of them.


#!/bin/bash
for snapshot in `zfs list -H -t snapshot | cut -f 1`
do
zfs destroy $snapshot
done

Works, but a bit plain.

next up: the oneliner


zfs list -H -t snapshot | cut -f 1 | tr '\n' ','| xargs zfs destroy

(-H removes the heading from the output which is needed for scripts, cut -f 1 takes the first chunk,tr takes the newline and replaces it with a comma, xargs feeds zfs destroy with the generated list)

zfs list -t snapshot -H | cut -f 1 | xargs -n 1 zfs destroy -v

(same as above, except here we are not substituting the newline with a comma using tr, but telling xargs to give one line at a time as a argument to zfs destroy.)

finally: RTFM (man zfs)
you can define a range of snapshots with the %-sign.

zfs destroy -v tank@fresh%current

works fine, but if you want to clean them all out you can do a single %-sign and get them all.

zfs destroy -v tank@%

and be done with it. although there seems to be a problem if there are dependencies on the snapshots. i keep getting a clean -vn output with snapshots but when removing the -n i get real zfs-filesystems that want to be deleted and unmounted first. stick to the oneliner for now.

Hint: use zfs destroy -nv for a test-run to check your selection (-n for a dry run and -v for verbose output). use -r for recursive deletion, -R for recusive deletion of snapshots with dependencies.