Reverting a Git Merge

Sometimes you get in a situation--and this is a no-judgement zone, we've all been there--where you merge branches and you messed up and need to undo the merge because, well, because your co-workers are kind of mad you broke the project. Let's say that happened. How do you revert a merge?

Image

Some­times you get in a sit­u­a­tion — and this is a no-judge­ment zone, we’ve all been there — where you merge branch­es and you messed up and need to undo the merge because, well, because your co-work­ers are kind of mad you broke the project.

Let’s say that hap­pened. How do you revert a merge?

We have a my_feature_branch that I’ve been work­ing in. We also have a develop branch that I merge into and deploy to my testing/​staging server. 

git checkout develop
git merge my_feature_branch

My merge of my_feature_branch into develop broke the site. I need to save myself from fur­ther embar­rass­ment in front of my team, so let’s undo the merge into develop.

Because the merge is a com­mit that points the HEAD to a spe­cif­ic com­mit, we can undo the merge com­mit and roll back to the pre-merge state.

To revert the pre­vi­ous com­mit (our merge com­mit), we do:

git revert HEAD

We can also spec­i­fy the exact merge com­mit that we want to revert using the same revert com­mand but with a cou­ple addi­tion­al options.

git revert -m 1 dd8d6f587fa24327d5f5afd6fa8c3e604189c8d4>

We spec­i­fy the merge using the SHA1 hash of the merge com­mit. The -m fol­lowed by the 1 indi­cates that we want to keep the par­ent side of the merge (the branch we are merg­ing into).

The out­come of this revert is that Git will cre­ate a new com­mit that rolls back the changes from the merge. 

We are saved from embar­rass­ment! The project is work­ing again. Now back to work to fig­ure out why that merge broke the commit.