19

Say I have an existing branch B (if it makes a difference, it's remote).

I also have a branch A (either local or remote). I would like branch B to be exactly like A. If I understand correctly, merge doesn't make the branches identical, there still can be something in branch B that wasn't on branch A and it will remain there after doing git checkout B followed by git merge A. Do I understand correctly?

Of course, I can just delete branch B and create a new branch B from A. Is that the best way?

note just to clarify it: I want to keep branch B alive because of deployment configuration. If I delete and recreate I'll need to do another thing manually for deployment.

Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114

4 Answers4

35

git keeps track of the history of development. Thus, to make a branch exactly like another branch, you just need to:

git checkout <branch B>
git reset --hard <branch A>
git push --force origin <branch B>

Of course, doing this you will lose the development history that was on branch B.

houtanb
  • 3,852
  • 20
  • 21
1

Sounds like you just want to rename branchB.

git branch -m branchB new_name_for_branchB
git branch branchA branchB

Now new_name_for_branchB refers to the same commit that branchB used to, and branchB now refers to the same commit as branchA. The two branches A and B are still distinct, though.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can certainly do this but do you really want to? If B is remote it also means someone else might have it checked out and rewriting will be confusing, at best, for them...

Anyway

git checkout B       # get B
git reset --hard A   # change B to be exactly like A
git push --force     # push B to remote, use --force to overwrite B (not normally allowed)
Andreas Wederbrand
  • 38,065
  • 11
  • 68
  • 78
-1

the git reset --hard as described by others will synch your local branch A to the (remote) branch B whenever you run it.

If the (remote) branch is a "live branch" (that is, people (possibly other people than you; possibly from multiple localtions/hosts/...) commit to it), it will evolve over time. In order to make your branch "follow" the remote branch through new changes, you might want to set it up as tracking.

git branch --set-upstream A origin/B

then, whenever you pull from the remote origin, it will (try to) sync your local copy A.

umläute
  • 28,885
  • 9
  • 68
  • 122