Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 2Shirt/6270696b857cecdf4a6d0d4f4fedeb3b to your computer and use it in GitHub Desktop.
Save 2Shirt/6270696b857cecdf4a6d0d4f4fedeb3b to your computer and use it in GitHub Desktop.
Complete git repository backup script to Backblaze B2
#!/bin/bash
# Script to backup git repo to Backblaze B2
# Set bucket, temp_dir, password and account to use for the backup. I keep mine in local env vars
# These are set by localrc which lives on an encrypted home directory and is executed by my bashrc
# Ensure you have authorized the B2 command line tool with the correct account AND added your SSH
# public key to your github account, if you need to backup private repositories.
# To restore this repo in the future, download it from B2, extract it and then use this command:
# cd old-repository.git
# git push --mirror https://github.com/exampleuser/new-repository.git
# Future details are here: https://help.github.com/articles/duplicating-a-repository/
set -o errexit
set -o errtrace
set -o nounset
set -o pipefail
b2_bucket="${BACKBLAZE_BUCKET}"
b2_cmd="b2"
b2_id="${BACKBLAZE_ID}"
b2_key="${BACKBLAZE_KEY}"
date="$(date '+%F_%H%M%z')"
github_account="${GITHUB_ACCOUNT}"
temp_dir="${BACKUP_TEMP_DIR}"
# Check for backblaze-b2
# Check for b2 cmd
if which backblaze-b2 >/dev/null 2>&1; then
# Arch Linux uses this name
b2_cmd="backblaze-b2"
elif ! which b2 > /dev/null 2>&1; then
echo "Error B2 command-line tool not found"
exit 1
fi
# Setup repository to ${1}
repository="${1}"
if [[ "${repository: -4:4}" == ".git" ]]; then
repository="${repository:0: -4}"
fi
# Create the backup directory
mkdir -p "${temp_dir}"
pushd "${temp_dir}" > /dev/null
echo "Backing up ${repository}"
git clone --mirror --verbose \
"https://github.com/${github_account}/${repository}.git" \
"${repository}-${date}.git"
if [ $? -ne 0 ]; then
echo "Error cloning ${repository}"
exit 1
fi
tar cpzf "${repository}-${date}.git.tgz" "${repository}-${date}.git"
if [ $? -ne 0 ]; then
echo "Error compressing ${repository}"
exit 1
fi
# Authorize B2 account
"${b2_cmd}" authorize-account "${b2_id}" "${b2_key}"
if [ $? -ne 0 ]; then
echo "Error authorizing Backblaze B2 account"
exit 1
fi
if [[ -f "${repository}-${date}.git.tgz" ]]; then
"${b2_cmd}" upload-file "${b2_bucket}" \
"${repository}-${date}.git.tgz" \
"${github_account}/${repository}-${date}.git.tgz"
fi
if [ $? -ne 0 ]; then
echo "Error uploading ${repository} to Backblaze B2"
exit 1
fi
#delete tar file and checked out folder
/bin/rm "${temp_dir}/${repository}-${date}.git.tgz"
/bin/rm -rf "${temp_dir}/${repository}-${date}.git"
if [ $? -ne 0 ]; then
echo "Error removing temp files"
exit 1
fi
popd > /dev/null
echo "Succesfully backed up ${repository}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment