Skip to content

Instantly share code, notes, and snippets.

@tobiastom
Last active December 23, 2015 21:19
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tobiastom/6695787 to your computer and use it in GitHub Desktop.
Clone all repositories from a remote SSH server.

Backup repositories

The idea of this script is to backup all repositories from a remote SSH server.

It will search for ´.git´ directories inside the home directory of the "git" user. By default it is the current user, but can be configured by changing the $GIT_USER variable at the top of the script.

All repositories will be cloned into the current working directory.

If there is a previous clone of the repository at the given destination, it will obviously only make a new pull.

#!/bin/bash
# Address of the server we want to backup from. This does not include the
# user. We assume the user to find the repositories is the current one, and
# the one we clone with is the one specified below
SERVER=example.com
# The user inside whoms directory the repositories are stored
GIT_USER=$(whoami)
# The command that will be execited to find all the repositories
# We search for `*.git` to find bare repositories and `.git` for "usual"
# repositories.
COMMAND="find /home/$GIT_USER -name \"*.git\" -or -name \".git\" -type d -maxdepth 3"
# Execute the command an get the result
DIRECTORIES=$(ssh $SERVER $COMMAND)
# Now loop through the directories that we found.
for FILE in $DIRECTORIES; do
# Get the basename of the path (only the name of the directory)
BASENAME=$(basename $FILE);
# If the basename is `.git`, we do have a non bare repository. So we remove
# the git directory and use the parent one
if [ "$BASENAME" == ".git" ]; then
DIRECTORY=$(dirname $FILE)
# Otherwise the repository ends with a `.git` extension (e.g. `sample.git`)
# and we can directly use it
else
DIRECTORY=$FILE
fi
# Build the name of the repository with only the last two components
NAME=$(basename $(dirname $DIRECTORY))/$(basename $DIRECTORY)
# Create the repository URL
REPOSITORY=$GIT_USER@$SERVER:$NAME
# Build the destination where the repository will be stored
# This is different then $NAME because we do not want .git in our cloned
# repository.
DESTINATION=$(dirname $NAME)/$(basename -s .git $NAME)
echo
echo "### Working on repository $NAME"
# If the destination already exists, we want to pull for changes
if [ -d $DESTINATION ]; then
echo "Pulling updates"
# Execute the pull inside a "subshell". Otherwise we would change our
# current working directory.
RESULT=$(
cd $DESTINATION && git pull $REPOSITORY
)
# otherwiese we just make a new clone of the repository
else
echo "Cloning new repository $NAME"
RESULT=$(git clone $REPOSITORY $DESTINATION)
fi
echo $RESULT | sed "s/^/ /"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment