Skip to content

Instantly share code, notes, and snippets.

@oxagast
Created August 1, 2025 05:22
Show Gist options
  • Save oxagast/87da9e16c487d69f04a949a33db29f9d to your computer and use it in GitHub Desktop.
Save oxagast/87da9e16c487d69f04a949a33db29f9d to your computer and use it in GitHub Desktop.
Generates ZFS filesystem snapshots and leaves three trailing snaps
#!/usr/local/bin/bash
# num snapshots to hold back
KEEP=3
# Define the ZFS filesystem to snapshot
ZFS_FILESYSTEM="storage"
# Define the snapshot name prefix
SNAPSHOT_PREFIX="snap"
# Get the current date in a suitable format for the snapshot name
SNAPSHOT_DATE=$(date +%Y%m%d%H%M%S)
# Create the new snapshot
echo "Creating new snapshot: $ZFS_FILESYSTEM@$SNAPSHOT_PREFIX-$SNAPSHOT_DATE"
zfs snapshot "$ZFS_FILESYSTEM@$SNAPSHOT_PREFIX-$SNAPSHOT_DATE"
# Get a list of snapshots for the specified filesystem, sorted by creation date (newest first)
# awk prints the snapshot name (first feild).
SNAPSHOTS=$(zfs list -t snapshot | grep "$ZFS_FILESYSTEM" | awk '{print $1}' | sort -r)
# Count the number of snapshots
NUM_SNAPSHOTS=$(echo "$SNAPSHOTS" | wc -l)
KEEPTAIL=$(($KEEP + 1))
# If there are more than two snapshots (newest + one old version)
if [ "$NUM_SNAPSHOTS" -gt $KEEP ]; then
# Loop through snapshots to identify and destroy older ones, keeping only the two most recent
# The snapshots are sorted newest first, so we want to keep the first two and destroy the rest.
# 'tail -n +3' starts from the third line, effectively giving us snapshots older than the third newest.
OLD_SNAPSHOTS=$(echo "$SNAPSHOTS" | tail -n +$KEEPTAIL)
for OLD_SNAP in $OLD_SNAPSHOTS; do
echo "Destroying old snapshot: $OLD_SNAP"
zfs destroy "$OLD_SNAP"
done
else
echo "Fewer than two snapshots found, no old snapshots to delete."
fi
mailx -s "Fileserver: snapshot taken" [email protected] <<< \
"The fileserver has generated a filesystem snapshot of $ZFS_FILESYSTEM at $ZFS_FILESYSTEM@$SNAPSHOT_PREFIX-$SNAPSHOT_DATE"
echo "Snapshot process complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment