Skip to content

Instantly share code, notes, and snippets.

@vizv
Created June 19, 2017 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vizv/06075c40908e3ddbeb8ce8037af97fcf to your computer and use it in GitHub Desktop.
Save vizv/06075c40908e3ddbeb8ce8037af97fcf to your computer and use it in GitHub Desktop.
viz-snapshot
# viz-snapshot defaults file.
BTRFS_ROOT_DEV='/dev/mapper/root'
BTRFS_SUBVOLS='system/awesome-root data/awesome-home-viz'
#!/bin/sh
# btrfs snapshot script.
# By Viz, Apr 11, 2017
# exit the script on failure.
set -e
# load defaults.
[ -f "/etc/default/viz/snapshot" ] && source "/etc/default/viz/snapshot"
BTRFS_ROOT_DEV=${BTRFS_ROOT_DEV:-/dev/mapper/root}
# create a temporary directory for mount the btrfs root.
TMP_MNT="$(mktemp -u)"
[ -e "$TMP_MNT" ] && {
echo "[!] Error: directory \"${TMP_MNT}\" already exists!" >&2
exit 1
}
mkdir -p "$TMP_MNT"
[ ! -d "$TMP_MNT" ] && {
echo "[!] Error: failed to create \"${TMP_MNT}\" directory!" >&2
exit 1
}
# mount the btrfs root.
mount -t btrfs "$BTRFS_ROOT_DEV" "$TMP_MNT"
echo "[+] btrfs root is mounted successfully."
# get current time as tag.
TAG="$(date '+%F_%H:%M')"
echo "[+] set snapshot tag to \"${TAG}\"."
# snapshot all configured sub-volumes.
pushd "$TMP_MNT" >/dev/null
for SUBVOL in $BTRFS_SUBVOLS; do
[ -z "$(ls -A "$SUBVOL" 2>/dev/null)" ] && {
echo "[-] empty sub-volume found: \"${SUBVOL}\", skip." >&2
continue
}
[ -e "${SUBVOL}-${TAG}" ] && {
echo "[-] snapshot target path has been occupied, skip." >&2
continue
}
btrfs subvolume snapshot "$SUBVOL" "${SUBVOL}-${TAG}"
echo "[+] btrfs snapshot has taken for sub-volume \"${SUBVOL}\"."
done
popd >/dev/null
echo "[+] all btrfs snapshot has taken."
# unmount the btrfs root and cleanup.
umount -l "$TMP_MNT" # not a bug: let it fail if failed to unmount.
rmdir "$TMP_MNT" # not a bug: let it fail if the directory is not empty.
# done.
echo "[+] done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment