Skip to content

Instantly share code, notes, and snippets.

@uchida
Last active October 6, 2015 02:47
Show Gist options
  • Select an option

  • Save uchida/2922482 to your computer and use it in GitHub Desktop.

Select an option

Save uchida/2922482 to your computer and use it in GitHub Desktop.
A ZFS snapshots rotation script
#!/usr/bin/env bash
# A ZFS snapshots rotation script
# by Akihiro Uchida, CC0 dedicated to the public domain
# see http://creativecommons.org/publicdomain/zero/1.0/
usage="usage: $(basename $0) [-v] filesystem generation"
die() {
echo "$@" >&2
exit 1
}
VERBOSE=false
while getopts ":v" opt; do
case $opt in
v) VERBOSE=true;;
*) die $usage;;
esac
done
shift $((OPTIND - 1))
print() {
$VERBOSE && echo "$@"
}
if [ $# -ne 2 ]; then
die $usage
fi
filesystem=$1
generation=$2
pool=$(echo $filesystem | cut -d/ -f1)
if [ -z "$(zpool list $pool 2>/dev/null)" ]; then
die "zfs pool: $pool does not exist!"
fi
mntpt=$(zfs get -H mountpoint $pool | cut -f3)
path=$(echo $filesystem | sed -e "s|$pool|$mntpt|")
if ! [ -e "$path" ]; then
die "path to $filesystem: $path does not exist!"
fi
if ! [[ "$generation" =~ ^[0-9]+$ ]]; then
die "generation: $generation must be numeric value!"
fi
snapshots=$(zfs list -H -t snapshot | grep "$filesystem@" | cut -f1)
delete_list=$(echo "$snapshots" | sort -r | sed -e "1,${generation}d")
for snapshot in $delete_list; do
print "destroy $snapshot"
# ignore errors on destroy (snapshots may have non-zero userrefs)
zfs destroy $snapshot || :
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment