Undoing a 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 now what you wanted. You will wonder what steps to undertake to resolve the problem.

This snippet will help you to undo git rebase in a fast and straightforward way. The easiest way is to find the head commit of your branch as it was before the rebase started in the git reflog, by running :

Afterward, 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}

In this example, the old commit is HEAD5.

You can go on with checking the history by running:

git log HEAD@{5}

What is Git Rebase

Git rebase is aimed at moving or combining a range of commits into a new base commit. With the help of git rebase, you can change the basis of the present branch from one commit to another. As a result, the branch looks like it has been generated from another commit.

git reflog

The Usage of Git Rebase

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.


Do you find this helpful?

Related articles