Replace one git branch with the contents of another

December 21, 2015

At WebDevStudios we use branches as deployment channels in Beanstalk. Today I ran across a situation where one of the dev branches had significantly diverged from the production branch. difftool showed 988 differing files. Needless to say this caused some issues on the dev server.

I needed to sync the dev branch with the production branch by replacing everything in the dev branch. Here is how I did it:

All at once

[bash]
git checkout prod
git checkout -b new-dev
git merge -s ours dev
git checkout dev
git merge new-dev
git push dev
[/bash]

Breakdown

[bash]
git checkout prod
git checkout -b new-dev
[/bash]

Create a new branch off of the production branch that can merges can be tested in.

[bash]
git merge -s ours dev
[/bash]

using -s ours will essentially overwrite everything from dev with changes in new-dev (prod originally). If this switch is not used a lot of conflicts would have been introduced and I do not have enough scotch on hand to stop that headache.

[bash]
git checkout dev
git merge new-dev
gitpush dev
[/bash]

It is now safe to merge new-dev into dev. There should not be any conflicts. Push it out and the dev branch is now sync’d back with prod.

6 thoughts on “Replace one git branch with the contents of another

  1. Jean-Yves (March 7, 2018)

    THanks, you just saved me hours of pain – I needed exactly the same process 🙂

  2. Dave Clements (May 14, 2018)

    Just wanted to correct a slight syntax error in the final step of the breakdown. You’re missing a space between `git` and `push`

  3. Josh (May 14, 2018)

    Bless you sir. Bless you.

  4. Frank Meyfarth (June 6, 2018)

    Well done, sir. I have two recommendations:

    1. Name branches “source” and “target” to make it more clear which way the content is flowing.
    2. Remove the interims branch “new-dev” when you’re done.

  5. Trai Tran (October 10, 2018)

    Thank you so much! It very useful for me and solved fast my problem.

  6. Sangeeta Mahalingam (March 29, 2019)

    Thank you so much. This solution really help me alot 🙂

Leave a Reply to Dave Clements Cancel reply

Your email address will not be published. Required fields are marked *