Skip to content

Instantly share code, notes, and snippets.

@milhomem
Created March 12, 2016 14:30
Show Gist options
  • Save milhomem/2c0574eb08cecc0d6f97 to your computer and use it in GitHub Desktop.
Save milhomem/2c0574eb08cecc0d6f97 to your computer and use it in GitHub Desktop.
Backup git repository to another remote
#!/bin/bash
#
# Given a GIT repository with two remotes, uses one as `origin`
# and other as `destination` for the backup.
# Usage:
# /usr/bin/backup-all-git-repos.sh [repo-name]
# repo-name: Name of the repository to backup, is actually
# the directory of the repository in the FS.
# If specified only backups that repository.
#
# vim: et ts=4 sw=4:
set -e # Stop on errors
declare -r REPOSITORIES_DIRECTORY=/repositories
declare -r REMOTE_ORIGIN=origin
declare -r REMOTE_DESTINATION=bitbucket
# Re-indents input with a tab before all lines.
indent() {
sed "s/^/\t/"
}
push_changes_from_remote_to_another() {
[[ -z "$1" ]] && { echo "!!! Missing repository directory to backup!"; return 1; }
[[ -z "$2" ]] && { echo "!!! Missing remote name to fetch changes from!"; return 1; }
[[ -z "$3" ]] && { echo "!!! Missing remote name to send changes to!"; return 1; }
declare -r repository_dir=$1
declare -r origin_remote=$2
declare -r destiny_remote=$3
cd $repository_dir;
echo "Fetching changes from $origin_remote"
git fetch -v ${origin_remote} 2>&1
echo
branches=$(git branch -a | grep "remotes/${origin_remote}" | grep -v HEAD)
branch_quantity=$(git branch -a | grep "remotes/${origin_remote}" | grep -v HEAD | wc -l)
echo "Branches to update: $branch_quantity"
for remote in $branches ; do
BRANCH_NAME=$(echo $remote | grep -oE '[^/]+$')
echo "Pushing remote $remote -> $BRANCH_NAME"
git push -f $destiny_remote $remote:refs/heads/$BRANCH_NAME 2>&1 | indent
done
}
fetch_repository_list() {
only_repository_name=$1
if [ -z "$only_repository_name" ]; then
ls -d $REPOSITORIES_DIRECTORY/*
return 0;
fi
repo_full_path="${REPOSITORIES_DIRECTORY}/${only_repository_name}"
if [ ! -d $repo_full_path ]; then
echo "!!! Repository '${only_repository_name}' does not exist on $REPOSITORIES_DIRECTORY."
exit 1;
fi
echo $repo_full_path;
}
for dir in $(fetch_repository_list $1); do
echo "Backing up ${dir} ...";
push_changes_from_remote_to_another $dir $REMOTE_ORIGIN $REMOTE_DESTINATION | indent
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment