Last active
December 29, 2023 04:01
-
-
Save munnadroid/283a403a8fe024dd0f047cd6d80db939 to your computer and use it in GitHub Desktop.
Bash script to mirror from one git repo to another git repo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to handle non-critical errors | |
handle_minor_error() { | |
echo "Non-critical error on line $1" | |
} | |
# Trap errors | |
trap 'handle_minor_error $LINENO' ERR | |
# Check if enough arguments are provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <git-repo-url> <new-remote-url>" | |
exit 1 | |
fi | |
# Assign arguments to variables | |
GIT_REPO_URL=$1 | |
NEW_REMOTE_URL=$2 | |
REPO_NAME=$(basename "$GIT_REPO_URL" .git) | |
# Clone the repository | |
echo "Cloning repository..." | |
git clone "$GIT_REPO_URL" | |
# Change directory to the cloned repository | |
echo "Changing directory to ${REPO_NAME}..." | |
cd "$REPO_NAME" | |
echo "Current directory: $(pwd)" | |
# Fetch all branches from origin | |
git fetch origin | |
# Add new remote | |
echo "Adding new remote..." | |
git remote add gh "$NEW_REMOTE_URL" | |
# Get the name of the currently checked out branch | |
current_branch=$(git rev-parse --abbrev-ref HEAD) | |
# Checkout and track all branches except the current one | |
for branch in $(git branch -r | grep -v '\->' | sed 's/origin\///'); do | |
if [ "$branch" != "$current_branch" ]; then | |
git branch --track "$branch" "origin/$branch" || echo "Skipping branch $branch" | |
echo "Checked out and tracking branch: $branch" | |
fi | |
done | |
# Push all branches and tags to the new remote with --mirror | |
echo "Pushing to new remote..." | |
git push gh --mirror | |
# Go back one step and delete the repository directory | |
cd .. | |
rm -rf "$REPO_NAME" | |
echo "Repository cloned, mirrored to new remote, and directory cleaned up." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
./git-mirror-repo.sh <source_repo> <destination_repo>
In case of permission of execution issue:
chmod +x git-mirror-repo.sh