Last active
January 4, 2020 08:46
-
-
Save crazyboycjr/cdcacb515eb3096fd1a78a6908023fdd to your computer and use it in GitHub Desktop.
btrfs snapshot automation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Btrfs snapshot | |
[Service] | |
Type=oneshot | |
ExecStart=/usr/local/bin/do-btrfs-snapshot.sh | |
StandardOutput=journal | |
[Install] | |
WantedBy=multi-user.target |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Daily backup of Btrfs filesystem | |
[Timer] | |
OnCalendar=*-*-* 05:35:00 | |
RandomizedDelaySec=10min | |
Persistent=true | |
[Install] | |
WantedBy=timers.target |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
systemd files goes to
/usr/lib/systemd/system