Skip to content

Instantly share code, notes, and snippets.

@dvarrazzo
Created February 3, 2020 15:46
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 dvarrazzo/d5432e607f2cdd1160ab6112d29dc18d to your computer and use it in GitHub Desktop.
Save dvarrazzo/d5432e607f2cdd1160ab6112d29dc18d to your computer and use it in GitHub Desktop.
#!/bin/bash
# A backup solution based on rsync with hard links and no deletion of old images
# Deletion would be delegated to a script such as weeder
# https://pypi.org/project/weeder/
set -euo pipefail
set -x
dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
backup_source=root@nas
base_dir=/mnt/nasbkp/volume1
identity_key=~piro/.ssh/id_rsa-nasbkp
rsync_opts="--archive --hard-links --one-file-system --numeric-ids \
--exclude-from=${dir}/volume1.exclude --delete --delete-excluded"
# Verbosity
# rsync_opts="${rsync_opts} --info=progress2"
rsync_opts="${rsync_opts} -v"
# check if there is an interrupted backup or create a new backup dir
backup_dir=$(ls -1d "${base_dir}"/????????_????.tmp 2>/dev/null | head -1 || true)
if [ -z "${backup_dir}" ]; then
echo "creating a backup into ${backup_dir}"
backup_dir="${base_dir}/$(date +%Y%m%d_%H%M).tmp"
else
echo "continuing a backup already started into ${backup_dir}"
fi
# check if there is a previous dir to link
previous_dir=$(ls -1dr "${base_dir}"/????????_???? 2>/dev/null | head -1 || true)
if [ -n "${previous_dir}" ]; then
echo "hard-linking from ${previous_dir}"
rsync_opts="${rsync_opts} --link-dest=${previous_dir}"
fi
# Run an ssh agent if there isn't one already. Close it on leaving.
if [ -z "${SSH_AGENT_PID:-}" ]; then
eval `/usr/bin/ssh-agent`
trap 'eval `/usr/bin/ssh-agent -k`' 0
fi
# Load the identity file if not already there.
if ! ssh-add -l | grep -q $(ls ${identity_key}); then
ssh-add "${identity_key}"
fi
# copy files over
mkdir -p "${backup_dir}"
rsync ${rsync_opts} "${backup_source}": "${backup_dir}"
# copy successful: remove the tmp status
mv -v ${backup_dir} ${backup_dir/.tmp/}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment