Handy shell command to delete snapshots matching a query in bulk

Since the GUI doesn’t let you pick all items on the current page or mass select snapshots, e.g., delete everything matching the query (which would be really nice), this will do the same thing:

zfs list -t snapshot -o name,creation | grep '2024-09-23_' | awk '{print $1}' | xargs -n1 zfs destroy

In this case, I need to remove everything on one day so I could backup.

I made the mistake of turning delete empty snapshots ON.

Won’t make that mistake again.

2 Likes

Minor nitpick on style: grep is built into awk and xargs can be dropped, too, by printing out the complete commands and piping to shell:

zfs list -t snapshot -o name,creation | awk '/2024-09-23_/ { printf "zfs destroy %s\n", $1 }' | sh

For a dry run omit the trailing | sh, then when sure, type cursor up, append the pipe to shell, hit enter, done.

2 Likes

As far as scripting with ZFS goes, it can actually be pretty handy to learn how to use py-libzfs. GitHub - truenas/py-libzfs: Python libzfs bindings

Just bear in mind that it’s not thread-safe.

2 Likes

Not to :metal:spam my own post:metal:, but this is one of those instances where you create a checkpoint before attempting such a command or script, and then remove the checkpoint shortly after you confirm everything went smoothly.

3 Likes

One other random bit of errata about handling large numbers of snapshots:

Snapshot iteration is much faster if you limit yourself to attributes that can be gotten from a simple ZFS handle (e.g. name, createtxg) rather than requesting / parsing timestamps. Iterators in libzfs can handle start and end txgs.

1 Like

dang. you learn something new every day! checkpoints are like seatbelts… you wear them for a little bit and then remove them. :slight_smile:

Thank you for that post!