From ffde698626c3f5516d0fdd68d1db021aea48010d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?marc=20W=C3=A4ckerlin?= Date: Fri, 6 Oct 2017 16:50:54 +0200 Subject: [PATCH] added support for cron periods --- btrfs-snapshots.sh | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/btrfs-snapshots.sh b/btrfs-snapshots.sh index 008dfaf..456c16d 100755 --- a/btrfs-snapshots.sh +++ b/btrfs-snapshots.sh @@ -6,6 +6,19 @@ TMP_MNT=${TMP_MNT:-/var/tmp/btrfs-backup} vols=() del= dryrun=0 +periodity=${a%/*} +periodity=${periodity##*/} +if [[ $periodity =~ ^cron\... ]]; then + periodity=${periodity#cron} +else + periodity= +fi +case "$periodity" in + (.hourly) del=25;; + (.daily) del=8;; + (.weekly) del=5;; + (.monthly);; +esac while test $# -gt 0; do case "$1" in (-h|--help) cat < delete snapshots older than given number of days + -d, --del delete oldes snapshots beginning at -th ENVIRONMENT @@ -34,6 +47,19 @@ Creates a snapshot for all btrfs volumes specified. Snapshot is named from the subvol name or if there is no subvol, from the path by appending -snapshot-YYYY-MM-DD-HH-mm. +To create regular snapshots on a daily base, just run: + + sudo cp btrfs-snapshots.sh /etc/cron.daily/btrfs-snapshots + +If btrfs-snapshots is run from a cron.daily, cron.hourly, +cron. monthly or cron.weekly directory, the periodity is automatically +appended to the snapshot name, and the expiry is set meaningfull: + + - hourly → keep only 24 hours, --del 25 + - daily → keep only 7 days, --del 8 + - weekly → keep only 4 weeks, --del 5 + - monthly → old snapshots are not deleted + EOF exit;; (-n|--dry-run) dryrun=1;; @@ -72,19 +98,30 @@ for fs in ${BTRFS_VOLUMES}; do name=/${name//\//-}- fi fi - target="${name}snapshot-$(date +%Y-%m-%d-%H-%M)" + date="-$(date +%Y-%m-%d-%H-%M)" + target="${name}snapshot${periodity}" if test -n "$device"; then if test $dryrun -eq 1; then echo -e "→ \e[1mbackup ${subvol:+subvol $subvol of }$fs on $device\e[0m" echo " " mount "$device" "$TMP_MNT" - echo " " btrfs subvolume snapshot "${TMP_MNT}${subvol}" "${TMP_MNT}${target}" + echo " " btrfs subvolume snapshot "${TMP_MNT}${subvol}" "${TMP_MNT}${target}${date}" + if test -n "$del"; then + for f in $(ls -1 "${TMP_MNT}${target}${date}"-* | tail -n +"$del"); do + echo " " btrfs subvolume delete "$f" + done + fi echo " " umount "$TMP_MNT" else if mount | grep -q " on $TMP_MNT type "; then sudo umount "$TMP_MNT" fi sudo mount "$device" "$TMP_MNT" - sudo btrfs subvolume snapshot "${TMP_MNT}${subvol}" "${TMP_MNT}${target}" + sudo btrfs subvolume snapshot "${TMP_MNT}${subvol}" "${TMP_MNT}${target}${date}" + #if test -n "$del"; then + # for f in $(ls -1 "${TMP_MNT}${target}${date}"-* | tail -n +"$del"); do + # sudo btrfs subvolume delete "$f" + # done + #fi sudo umount "$TMP_MNT" fi else