Skip to content

Instantly share code, notes, and snippets.

@bketelsen
Last active June 29, 2024 22:32
Show Gist options
  • Save bketelsen/941930f8ec93d2f8f0c2217c1460e9bd to your computer and use it in GitHub Desktop.
Save bketelsen/941930f8ec93d2f8f0c2217c1460e9bd to your computer and use it in GitHub Desktop.
incremental btrfs snapshots sent to remote synology
#!/bin/env bash
set -e
# This script is used to create incremental snapshots of the given btrfs volume.
# capture today's date
today=$(date +%Y%m%d)
# use yesterday's as base for incremental snapshot
yesterday=$(date -d "yesterday" +%Y%m%d)
# capture the date of 2 days ago for cleanup
twodaysago=$(date -d "2 days ago" +%Y%m%d)
# define the target directory to store snapshots
snapshot_dir="/var/.snapshots/"
target_dir="/volume1/NetBackup/snaps"
# ensure the target directory exists
if [ ! -d "$snapshot_dir" ]; then
sudo mkdir -p "$snapshot_dir"
fi
# create the snapshot
sudo btrfs subvolume snapshot -r /home /var/.snapshots/home-$today
# send the incremental snapshot
sudo btrfs send -p /var/.snapshots/home-$yesterday /var/.snapshots/home-$today | ssh [email protected] "sudo btrfs receive /volume1/NetBackup/snaps"
# if it's the first day of the week, create a weekly snapshot
if [ $(date +%u) -eq 1 ]; then
weeknum=$(date +%U)
sudo btrfs subvolume snapshot -r /home /var/.snapshots/home-weekly-$weeknum
sudo btrfs send -p /var/.snapshots/home-$yesterday /var/.snapshots/home-weekly-$weeknum | ssh [email protected] "sudo btrfs receive /volume1/NetBackup/snaps"
# delete weekly snapshots older than 4 weeks
ssh [email protected] "sudo btrfs subvolume delete /volume1/NetBackup/snaps/home-weekly-$(date -d '4 weeks ago' +%U)"
fi
# if its the first day of the month, create a monthly snapshot
if [ $(date +%d) -eq 1 ]; then
monthnum=$(date +%m)
sudo btrfs subvolume snapshot -r /home /var/.snapshots/home-monthly-$monthnum
sudo btrfs send -p /var/.snapshots/home-$yesterday /var/.snapshots/home-monthly-$monthnum | ssh [email protected] "sudo btrfs receive /volume1/NetBackup/snaps"
# delete monthly snapshots older than 4 months
ssh [email protected] "sudo btrfs subvolume delete /volume1/NetBackup/snaps/home-monthly-$(date -d '12 months ago' +%M)"
fi
# cleanup old snapshots locally
sudo btrfs subvolume delete /var/.snapshots/home-$twodaysago
# cleanup old daily snapshots on remote
ssh [email protected] "sudo btrfs subvolume delete /volume1/NetBackup/snaps/home-$twodaysago"
# exit
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment