Skip to content

Instantly share code, notes, and snippets.

@crazyboycjr
Last active January 4, 2020 08:46
Show Gist options
  • Save crazyboycjr/cdcacb515eb3096fd1a78a6908023fdd to your computer and use it in GitHub Desktop.
Save crazyboycjr/cdcacb515eb3096fd1a78a6908023fdd to your computer and use it in GitHub Desktop.
btrfs snapshot automation
[Unit]
Description=Btrfs snapshot
[Service]
Type=oneshot
ExecStart=/usr/local/bin/do-btrfs-snapshot.sh
StandardOutput=journal
[Install]
WantedBy=multi-user.target
[Unit]
Description=Daily backup of Btrfs filesystem
[Timer]
OnCalendar=*-*-* 05:35:00
RandomizedDelaySec=10min
Persistent=true
[Install]
WantedBy=timers.target
#!/bin/bash
MOUNTPOINT=/tmp/mnt/do-snapshot
mkdir -p $MOUNTPOINT
DEV=`mount | grep btrfs | grep 'subvol=/arch' | awk '{print $1}'`
# mount the root filesystem
mount -t btrfs -o rw,noatime,compress=lzo,ssd,discard,space_cache,autodefrag $DEV $MOUNTPOINT
cd $MOUNTPOINT/snapshots
function create_snapshot()
{
name=$1
suffix=`date +%Y%m%d`
if [ -d ${name}_bak_$suffix ]; then
number=1
while [ -d ${name}_bak_$suffix.$number ]; do
number=`expr $number + 1`
done
# create readonly snapshot
btrfs subvolume snapshot -r ../${name}/ ${name}_bak_$suffix.$number
else
# create readonly snapshot
btrfs subvolume snapshot -r ../${name}/ ${name}_bak_$suffix
fi
}
function remove_snapshot()
{
name=$1
suffix=`date +%Y%m%d -d "31 day ago"`
snapshots=`find . -maxdepth 1 -type d -name "${name}_bak_${suffix}*"`
if [ $? -eq 0 ]; then
for snapshot in ${snapshots}; do
# delete the snapshot
btrfs subvolume delete $snapshot
done
fi
}
# create arch subvol snapshot
create_snapshot arch
# create home subvol snapshot
create_snapshot home
# remove expired snapshots
remove_snapshot arch
remove_snapshot home
cd /tmp
umount $MOUNTPOINT
@crazyboycjr
Copy link
Author

systemctl enable btrfs-snapshot.timer
systemctl start btrfs-snapshot.timer
systemctl disable btrfs-snapshot.service

systemd files goes to /usr/lib/systemd/system

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment