Undo merges

suggest change

Undoing a merge not yet pushed to a remote

If you have not pushed the merge, you can move the branch back as in Return to a previous commit. A merge commit has extra pitfalls.

git reset --hard drops the merge commit from the current branch. Commits that came in from the other branch remain on that other branch. git log now shows both sides, so check the commit you name. Resetting to a commit on the other branch moves this branch there and drops commits that were only on this branch. --hard also discards uncommitted work.

git reset --hard <last commit from the branch you are on>

If the merge is the newest commit on this branch:

git reset --hard HEAD~

A revert is safer, in that it won’t destroy committed work, but involves more work as you have to revert the revert before you can merge the branch back in again (see the next section).

Undoing a merge pushed to a remote

Assume you merge in a new feature (add-gremlins)

git merge feature/add-gremlins
...
   #Resolve any merge conflicts
git commit #commit the merge
...
git push
...
   501b75d..17a51fd  master -> master

Afterwards you discover that the feature you just merged in broke the system for other developers, it must be undone right away, and fixing the feature itself will take too long so you simply want to undo the merge.

git revert -m 1 17a51fd
...
git push
...
   17a51fd..e443799  master -> master

At this point the gremlins are out of the system and your fellow developers have stopped yelling at you. However, we are not finished just yet. Once you fix the problem with the add-gremlins feature you will need to undo this revert before you can merge back in.

git checkout feature/add-gremlins
...
   #Various commits to fix the bug.
git checkout master
...
git revert e443799
...
git merge feature/add-gremlins
...
   #Fix any merge conflicts introduced by the bug fix
git commit #commit the merge
...
git push

At this point your feature is now successfully added. However, given that bugs of this type are often introduced by merge conflicts a slightly different workflow is sometimes more helpful as it lets you fix the merge conflict on your branch.

git checkout feature/add-gremlins
...
   #Merge in master and revert the revert right away.  This puts your branch in
   #the same broken state that master was in before.
git merge master
...
git revert e443799
...
   #Now go ahead and fix the bug (various commits go here)
git checkout master
...
   #Don't need to revert the revert at this point since it was done earlier
git merge feature/add-gremlins
...
   #Fix any merge conflicts introduced by the bug fix
git commit #commit the merge
...
git push

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents