Home > Mobile >  How to replace one git branch with another?
How to replace one git branch with another?

Time:12-07

Sometimes I will checkout a test branch to see if a rebase / whatever works. But this leaves me in a situation where I have some branch feat-234, and some branch test, and I want to replace feat-234 with test.

Example workflow:

# on branch feat-234
git checkout -b test
git rebase main 
# apply fixes required to make rebase work

At this point I want to use test instead of feat-234, as what I wanted to do has worked.

edit 1

I tried to do the following whilst on branch test:

  • git branch -D feat-234, delete feat-234
  • git branch -m feat-234`

I don't think this worked though as I think I've lost all the remote information that was on feat-234.

CodePudding user response:

After you've verified that test is exactly what you want the feature branch to become:

git checkout feat-234
git reset --hard test

and you're done. You'll probably need to push with --force as well, since you're not simply adding commits to the branch.

CodePudding user response:

I'd like to propose a minor tweak to your workflow, which may be slightly cleaner than your proposed process:

  1. When you wish to test something like a merge or rebase, don't bother using a branch at all until you decide you want to keep it:

git switch --detach # Note you can add a starting commit or branch name if desired

This is equivalent to moving off to another test branch like you did, but you simply haven't named the branch yet, and you possibly never will if you don't like the result. In this way you also don't have to delete any test branches when you're done. Now do whatever you're going to do for your test, in your case perhaps git rebase main.

  1. If you like the result and wish to make your current branch feat-234, simply:

git switch -C feat-234

This creates a new branch called feat-234 like -c would do, but the capital -C replaces the branch if it already exists, which in this case it does. Remote tracking information will be retained as well.

  • Related