Home > OS >  How could I replace an entire branch with another in Git?
How could I replace an entire branch with another in Git?

Time:12-22

I created a repo on GitHub and created a local repo, too. The one on GitHub has the default branch named "main" and the local one is named "master".

Everything up-to-date is in the local "master" branch, but when I push it, it gets pushed into the "master", not the default "main" branch (which only has outdated, so not important stuff).

Is there a way I could place everything from "master" to "main", without messing around with commits? Like, replace the entire "main" with the "master".

CodePudding user response:

  • commit your changes in your local master branch
  • create a new local branch named main from master
  • push to main branch

CodePudding user response:

Branches in Git just point at commit. You can rename your branch and tell it to use origin/main as its upstream.

Your repo and upstream look like this, presumably you've pushed. Your local master and upstream master are in sync. Your upstream main is on some old commit.

origin
A - B - C [main]
         \
          D - E - F [master]

local
A - B - C [origin/main]
         \
          D - E - F [master]
                    [origin/master]
  1. Checkout master.
  2. Rename master to main: git branch -m main
origin
A - B - C [main]
         \
          D - E - F [master]

local
A - B - C [origin/main]
         \
          D - E - F [main]
                    [origin/master]
  1. Set its upstream to main: git branch -u origin/main

Since your main is out of date, you should force push to replace its contents with your local master.

  1. git push --force
origin
A - B - C - D - E - F [master]
                      [main]

local
A - B - C - D - E - F [main]
                      [origin/master]
                      [origin/main]
  1. Delete origin/master: git push origin :master
origin
A - B - C - D - E - F [main]

local
A - B - C - D - E - F [main]
                      [origin/main]
  1. You may need to "prune" your remote tracking branches of the now deleted origin/master: git fetch --prune origin. You should set this to be the default behavior.

CodePudding user response:

Simply rename your local branch and then push:

git checkout master
git branch -m main
git push origin -u main
  •  Tags:  
  • git
  • Related