Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3537b7e

Browse files
committed
Add a script to automate ZFS snapshots cleanup.
1 parent ff15218 commit 3537b7e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

scripts/delete_old_zfs_snapshots.sh

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/bin/bash
2+
# 2019 © Postgres.ai
3+
4+
# Use this script with caution! Note that this script is going to destroy all ZFS snapshots
5+
# on the machine, except:
6+
# - the last $1 snapshots (the first parameter in the CLI call),
7+
# - those snapthots that are used now,
8+
# - snapshots having "clone" or "NAME" in the name (however, they are supposed to be
9+
# dependant; so with old 'main' snapshots, dependant ones will be deleted as well,
10+
# thanks to '-R' option when calling 'zfs destroy').
11+
#
12+
# Example of use:
13+
# bash ./scripts/delete_old_zfs_snapshots.sh 5
14+
15+
set -euxo pipefail
16+
17+
n=$1
18+
19+
if [[ -z "$n" ]]; then
20+
echo "Specify the number of snapshots to keep (Example: 'bash ./scripts/delete_old_zfs_snapshots.sh 5' to delete all but last 5 snapshots)."
21+
else
22+
sudo zfs list -t snapshot -o name \
23+
| grep -v clone \
24+
| grep -v NAME \
25+
| head -n -$n \
26+
| xargs -n1 --no-run-if-empty sudo zfs destroy -R
27+
fi
28+
29+
## An example of crontab entry, setting up auto-deletion of all unused ZFS snapshots except the last 3 ones.
30+
## 0 6 * * * sudo zfs list -t snapshot -o name | grep -v clone | grep -v NAME | head -n -3 | xargs -n1 --no-run-if-empty sudo zfs destroy -R 2>&1 | logger --stderr --tag "cleanup_zfs_snapshot"

0 commit comments

Comments
 (0)