How to Undo Git Rebase

Suppose you have performed the git rebase command on the local git branch and pushed it to the remote. Then you realize that it is not what you wanted. You will wonder what steps to undertake to resolve the problem.

Steps to undoing git rebase

This snippet will help you undo git rebase in a fast and straightforward way:

If you have uncommitted local changes, then back up all of them, otherwise, they will be lost.

Finding head commit

Run git reflog to see all your previous operations and, then, find the head commit of your branch as it was before the rebase started. The commit ID will look like this HEAD@{5}:

git reflog

Resetting to the commit

After finding out to what commit where you want to go back, it is necessary to reset the current branch to it, using the git reset command. Note that you must be sure before running the git reset command with the --hard option like this:

git reset --hard HEAD@{5}

The given command only moves the local branch to HEAD@{5}.

Pushing to remote

Now you can check the status of your local branch using git status.

git status

If you see the given message, it means that your local branch and the remote one have diverged as the local branch has gone back to a previous commit while the remote one is still ahead.

 On branch myBranch
 Your branch and 'origin/myBranch' have diverged

To fix that, force your remote branch to get back to where your local branch is:

git push --force

Resetting branch

If you have changed your mind, you can reset your branch with the current remote branch (suppose, the name of remote is origin, which is by default) as follows:

git reset --hard origin/HEAD

The git rebase Command

First of all, this command is necessary to maintain a linear project history. Suppose that your master branch progresses as soon as you begin working on a feature branch. You wish to check the last updates of your master branch in the feature branch, but the master branch history must be kept clean. We can distinguish two modes of the git rebase commands. They are standard mode and interactive. In the standard mode, the commits are automatically taken in the current working branch and applied to the head of the passed branch. Your current branch will be rebased into the <base>. The interactive rebasing session begins by running the -i flag. The interactive mode allows altering individual commits in the process. It gives you an opportunity to clean up the history by changing, splitting and removing existing commits. It looks more like git commit-amend on steroids.

What is Git Reflog

Git keeps the record of updates to branches. It is possible due to a mechanism called reference logs or reflogs. The git reflog command allows you to get back to the commits even to the ones that have not been referenced by any tag or branch. After rewriting the history, git reflog involves information about the previous state of the branches and allows returning to that state whenever needed.