DEV Community

foadlind
foadlind

Posted on • Originally published at practicalgit.com

Undo a merge or a rebase

Have you merged the wrong branch into your branch? or maybe you rebased your branch on the main branch but something
went wrong during the process? Don't worry! You can undo a merge/rebase process fairly easily.

Before doing a dangerous operation, like merging or rebasing, Git saves your previous HEAD location in a special
variable called ORIG_HEAD. This way you can always go back to where HEAD was before you started the operation.

Let's say I have a branch called feature_1. I have accidentally merged the wrong branch into it. Instead of merging
main, I merged develop to it (commit af735d2). I would like to undo this operation.

*   af735d2 (HEAD -> feature_1) Merge branch 'develop' into feature_1
|\
| * db7d7a6 (develop) add login button
| * 2f0ae72 (main) add test fixtures
* | 2d487f5 create user profile page
|/
* 2f591bd fix bug #1
* 290fc8b add db config file
Enter fullscreen mode Exit fullscreen mode

Before I did the merge, Git saved the value of the previous HEAD location to the ORIG_HEAD variable. In this case,
2d487f5.
To remove the last commit I can instruct Git to reset to the location of ORIG_HEAD like this:

(feature_1)$ git reset --hard ORIG_HEAD
Enter fullscreen mode Exit fullscreen mode

Now my commit tree is clean, and I am back to where I was before the wrong merge.
Notice that the merge commit is removed:

* db7d7a6 (develop) add login button
* 2f0ae72 (main) add test fixtures
| * 2d487f5 (HEAD -> feature_1) create user profile page
|/
* 2f591bd fix bug #1
* 290fc8b add db config file
Enter fullscreen mode Exit fullscreen mode

You can use the same command for undoing a rebase.


signup

Top comments (0)