I created an experimental branch from master, and made four commits on the experimental branch. The master, in the mean time, still remains where it last was. Now, I want to merge my experimental branch in such a way that I will be able to easily undo this merge in future.
When I tried searching, the easiest way to undo a merge seems to me like git revert hash_of_merge_commit
.
However, this only works when I get a merge commit hash when merging my master with experimental branch. In this case, since master's HEAD has not progressed, when I try to merge, I just get four new commits added to master, and this would mean that to undo this merge, I would need to manually remember and revert each of these individual commits in future.
Any better way to do this?
You can undo a Git merge using the git reset –merge command. This command changes all files that are different between your current repository and a particular commit. There is no “git undo merge” command but the git reset command works well to undo a merge.
In case you are using the Tower Git client, undoing a merge is really simple: just press CMD+Z afterwards and Tower will undo the merge for you!
You can use the git reset --merge command. You can also use the git merge --abort command.
Now, if you have already pushed the merged changes you want to undo to your remote repository, you can right-click on the merge commit and select Revert commit from the context menu.
The other answerers seem to be concerned with preventing this from happening in the first place. If a fast-forwarded merge has already occurred and been pushed, here's a solution:
git checkout -b my-undo-branch
git reflog show master
- find the last commit before the mergegit reset --keep SHA
- using the SHA from the previous stepAt this point, verify that this branch is in the state that you want master
to be in. Now it's just a matter of taking the diff between those two branches and committing it to master:
git checkout master
git diff master my-undo-branch --no-prefix > patchfile
patch -p0 < patchfile
Then, finally, delete patchfile
, git add
all the changes, and git commit
them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With