How to Undo Rebase in Git

Azhar Bashir Khan Feb 02, 2024
How to Undo Rebase in Git

This tutorial will talk about undoing a rebase done on a branch in Git.

Rebasing is the operation of moving the base of a branch to a newer base. Suppose we have a feature branch based on the main branch. Then, the main branch has some new commits; we may want to rebase the feature branch based on those new ones.

We may re-think this rebase operation. We no longer want to base the new feature branch on the new commits in the main branch.

We want the feature branch to be based on the commits when we first branched it from the main branch. Thus, to achieve this, we now need to undo the rebase operation done on the branch.

We will now illustrate this with an example.

Using git reflog and git reset to Undo a rebase Done on a Branch in Git

Let’s say we have a main branch, and we have created a new branch feature1 on top of it.

And let’s say some commits have happened in the main branch. We have done a rebase of the new branch feature1 based on those new commits. This is the operation we want to undo.

To undo the rebase, we can use the reflog command of Git. Using git reflog, we can determine the branch’s head commit immediately before the rebase starts.

We will now run the git reflog command on the branch feature1 (one on which rebase was done)

$ git reflog

b745978 HEAD@{0}: rebase: that commit
4sd7c1c HEAD@{1}: rebase: this commit
adf3d3d HEAD@{2}: checkout: moving from main to feature1
...

We can see that HEAD@{2} was the commit just before the rebase operation.

We can use git reset to reset the branch to this commit as follows.

$ git reset HEAD@{2} --hard

After executing the above command, the branch feaure1 is now in a state just before the rebase.

Alternatively, one can also undo a rebase using git reset as follows.

$ git reset --hard ORIG_HEAD

The ORIG_HEAD is created by commands that drastically move your HEAD to record the position of the HEAD before their operation so that you can easily change the tip of the branch back to the state before you run them.

The caveat to this alternative approach is that no other operations should have been done after the un-wanted rebase that may change the ORIG_HEAD viz. reset, rebase, or merge.

Thus, we can undo an un-wanted rebase on a branch in Git through these methods.

Related Article - Git Rebase