Last active
May 23, 2024 08:53
-
-
Save iraklisg/7742057a0287eb83cbd751354198243b to your computer and use it in GitHub Desktop.
This shell script is used to update the remote repositories of a local Git repository
This file contains 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 | |
# This script updates the remote repositories of a local Git repository. | |
# It requires two arguments: the local repository path and the new GitHub URL. | |
# The script navigates to the provided repository path. | |
# If the directory does not exist, it exits with an error message. | |
# It adds a new remote called "github" with the provided GitHub URL. | |
# The current "origin" remote is renamed to "bitbucket". | |
# The "github" remote is then renamed to "origin". | |
# The script fetches all updates from the new origin. | |
# It then iterates over all branches in the local repository. | |
# For each branch, it checks if it was tracking the old "bitbucket" remote. | |
# If it was, the script unsets the upstream and sets it to track the new "origin". | |
# Check if the correct number of arguments is provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <REPO_PATH> <GITHUB_URL>" | |
exit 1 | |
fi | |
# Variables | |
REPO_PATH=$1 | |
GITHUB_URL=$2 | |
GITHUB_REMOTE="github" | |
BITBUCKET_REMOTE="bitbucket" | |
# Ensure you are in the correct repository directory | |
cd "$REPO_PATH" || { echo "Directory $REPO_PATH not found"; exit 1; } | |
# Add the new remote | |
git remote add "$GITHUB_REMOTE" "$GITHUB_URL" | |
# Rename the remotes | |
git remote rename origin "$BITBUCKET_REMOTE" | |
git remote rename "$GITHUB_REMOTE" origin | |
# Fetch updates from the new origin | |
git fetch --all | |
# Update the tracking branches | |
for branch in $(git branch | sed 's/^..//'); do | |
# Get the current upstream of the branch | |
current_upstream=$(git for-each-ref --format='%(upstream:short)' refs/heads/"$branch") | |
# If the branch was tracking 'bitbucket', update it to track 'origin' | |
if [[ $current_upstream == bitbucket/* ]]; then | |
git branch --unset-upstream "$branch" | |
git branch -u origin/"$branch" "$branch" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment