-
Notifications
You must be signed in to change notification settings - Fork 1
/
zfs-snapshot-cleanup.bash
99 lines (92 loc) · 2.38 KB
/
zfs-snapshot-cleanup.bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/bin/bash
for arg in "$@"
do
case $arg in
--dataset=*)
DATASET="${arg#*=}"
shift
;;
--keepdays=*)
KEEPDAYS="${arg#*=}"
shift
;;
--include=*)
INCLUDE="${arg#*=}"
shift
;;
--exclude=*)
EXCLUDE="${arg#*=}"
shift
;;
--force)
FORCE="TRUE"
shift
;;
*)
;;
esac
done
if [[ $DATASET == '' ]]
then
echo "--dataset parameter must be set"
exit 1
fi
if [[ ! $KEEPDAYS =~ ^[0-9]+$ ]]
then
echo "--keepdays parameter must be an integer"
exit 1
fi
SKIPFILESYSTEMREGEX='.system|/sys/swap'
SNAPSHOTSTODELETE=()
TODATE=$(date -n -v -${KEEPDAYS}d +"%s")
FILESYSTEMS=$(zfs list -H -t filesystem,volume -o name $DATASET | egrep -v $SKIPFILESYSTEMREGEX | sort)
for FILESYSTEM in $FILESYSTEMS
do
if [[ -z "$INCLUDE" && -z "$EXCLUDE" ]]
then
SNAPSHOTS=$(zfs list -H -r -t snapshot -o name -S creation $FILESYSTEM)
elif [[ -z "$INCLUDE" && ! -z "$EXCLUDE" ]]
then
SNAPSHOTS=$(zfs list -H -r -t snapshot -o name -S creation $FILESYSTEM | egrep -v "$EXCLUDE")
elif [[ ! -z "$INCLUDE" && -z "$EXCLUDE" ]]
then
SNAPSHOTS=$(zfs list -H -r -t snapshot -o name -S creation $FILESYSTEM | egrep "$INCLUDE")
elif [[ ! -z "$INCLUDE" && ! -z "$EXCLUDE" ]]
then
SNAPSHOTS=$(zfs list -H -r -t snapshot -o name -S creation $FILESYSTEM | egrep "$INCLUDE" | egrep -v "$EXCLUDE")
fi
for SNAPSHOT in $SNAPSHOTS
do
SNAPSHOTDATE=$(date -j -f "%a %b %d %H:%M %Y" "$(zfs list -H -r -t snapshot -o creation $SNAPSHOT)" +"%s")
if ((SNAPSHOTDATE <= $TODATE))
then
SNAPSHOTSTODELETE+=( $( echo $SNAPSHOT ) )
fi
done
done
if [[ ! $SNAPSHOTSTODELETE == '' && ! -z $SNAPSHOTSTODELETE ]]
then
if [[ $FORCE == 'TRUE' ]]
then
for SNAPSHOT in ${SNAPSHOTSTODELETE[@]}
do
zfs destroy $SNAPSHOT
done
else
for SNAPSHOT in ${SNAPSHOTSTODELETE[@]}
do
echo "$SNAPSHOT"
done
echo
read -p "Are you sure you want to destroy the above ($(echo "${SNAPSHOTSTODELETE[@]}" | wc -w | tr -d '[:space:]')) snapshots? " -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
for SNAPSHOT in ${SNAPSHOTSTODELETE[@]}
do
echo "zfs destroy $SNAPSHOT"
zfs destroy $SNAPSHOT
done
fi
fi
fi