BtrFS Snapshots w/ Samba

Mon 16 March 2015

The following is a script I wrote that will take snapshots of a BtrFS subvolume and name them in a convention that works with Samba's VFS shadow_copy module.

#!/bin/bash

set -e
set -u
#set -x
shopt -s extglob

if [ $# -ne 3 ]
then
    echo "Usage: $0 /path/to/subvol /path/to/snaps NUM_SNAPSHOTS"
    exit 0
fi

SUBVOLUME=$1
SNAPSHOTS=$2
NUM_SNAPS=$3

echo "---- Started processing at $(date) ----"

# Remove trailing slashes, unless it is root
if [ $SUBVOLUME != '/' ]
then
    SUBVOLUME="${SUBVOLUME%%+(/)}"
fi
if [ $SNAPSHOTS != '/' ]
then
    SNAPSHOTS="${SNAPSHOTS%%+(/)}"
fi

# Take snapshot
btrfs subvolume snapshot -r "$SUBVOLUME" "$SNAPSHOTS/$(date -u [email protected]%Y.%m.%d-%H.%M.%S)"

# Delete extra snapshots
num_existing=$(ls -1d $SNAPSHOTS/* | wc -l)
if [ $num_existing -gt $NUM_SNAPS ]
then
    let over=$num_existing-$NUM_SNAPS
    ls -1d $SNAPSHOTS/* | head -n $over | while read s
    do
        btrfs subvolume delete $s
    done
fi

echo ""
exit 0

View on GitLab

Raw Script