Skip to content

Instantly share code, notes, and snippets.

@sprhawk
Last active October 15, 2020 06:58
Show Gist options
  • Save sprhawk/a1dd8163d5480bcd2e681971de3da1bd to your computer and use it in GitHub Desktop.
Save sprhawk/a1dd8163d5480bcd2e681971de3da1bd to your computer and use it in GitHub Desktop.
btrfs send all snapshots to other directory
#!/bin/bash
usage()
{
echo "usage: `basename $0` from_directory to_directory"
}
if [ -z $1 ] || [ -z $2 ]; then
usage
exit 1
fi
# ROOT is the 1st argument, will search targets (udid)
FROM_ROOT=$1
# TO is the 2nd argument, will receive snapshot into
TO_ROOT=$2
# find all from target except snapshots
FROM_TARGETS=`find $FROM_ROOT -mindepth 1 -maxdepth 1 -type d | sort -n`
# there is an old backup dir has only snapshots
UNDER_SNAPSHOTS=0
rootbase=$(basename $FROM_ROOT)
if [ $rootbase = "snapshots" ]; then
UNDER_SNAPSHOTS=1
fi
for f in $FROM_TARGETS
do
# B is target UDID extracted from FROM path
TARGET_UDID=$(basename $f)
# filter out `snapshots`
if [ $TARGET_UDID != "snapshots" ]; then
# construct path to target's snapshots
FROM_UDID_ROOT="$FROM_ROOT/snapshots/$TARGET_UDID"
# check whether ROOT is snapshots
if [ $UNDER_SNAPSHOTS -eq 1 ]; then
FROM_UDID_ROOT="$FROM_ROOT/$TARGET_UDID"
fi
# construct path for receiving
TO_UDID_ROOT=$TO_ROOT/$TARGET_UDID
echo "mkdir -p $TO_UDID_ROOT"
mkdir -p $TO_UDID_ROOT
echo "Starting sending in $TARGET_UDID ..."
RET=0
# # LAST is used to keep previous/parent snapshot path
# LAST_UDID_TARGET=`find $TO_UDID_ROOT -mindepth 1 -maxdepth 1 -type d | sort -n | tail -n 1`
# echo "LAST: $LAST_UDID_TARGET"
# continue
LAST_UDID_TARGET=""
# find all snapshots under target's snapshots
FROM_UDID_TARGETS=`find $FROM_UDID_ROOT -mindepth 1 -maxdepth 1 -type d | sort -n`
for FROM_UDID_TARGET in $FROM_UDID_TARGETS
do
RET=0
TO_DATE=$(basename $FROM_UDID_TARGET)
if [ ! -d $TO_UDID_ROOT/$TO_DATE ]; then
if [ -z "$LAST_UDID_TARGET" ]; then
# didn't find a way to execute command with pipe inside a variable
CMD="btrfs send $FROM_UDID_TARGET | btrfs receive $TO_UDID_ROOT"
btrfs send $FROM_UDID_TARGET | btrfs receive $TO_UDID_ROOT
RET=$?
else
# use -p argument when there is already a snapshot copy
CMD="btrfs send -p $LAST_UDID_TARGET $FROM_UDID_TARGET | btrfs receive $TO_UDID_ROOT"
btrfs send -p $LAST_UDID_TARGET $FROM_UDID_TARGET | btrfs receive $TO_UDID_ROOT
RET=$?
fi
LAST_UDID_TARGET=$FROM_UDID_TARGET
if [ $RET -ne 0 ]; then
echo "failed to execute command: $CMD"
exit 1
fi
else
echo "existed: $TO_UDID_ROOT/$TO_DATE"
fi
done
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment