gitrecipes: the Git cookbook

How to undo a failed rebase

If a rebase you tried went through but did the wrong thing, it's too late to run git rebase --abort. So, what to do? That's where Git's reflog comes in. Whenever you change your branch in some way, it saves the state of the branch before your operation, so a reflog is basically a history of what your branch looked like before/after each operation.

Suppose you botched a rebase by accidentally removing an important commit. The most generic way of undoing this if you spot it immediately is rather simple:

git reset --hard @{1}

You may have to escape the curly braces so your shell doesn't try to eat them.

It gets more complicated if you perform a couple of commits before you spot the problem. In this case, we'll do almost the same thing, but save the botched state with the additional commits and, once we've unbotched things, transplant the new commits over. For that we use... you guessed it... rebase.

Suppose you're dealing with the branch master and made 4 good commits after your botched rebase (and none of them were merges. You'd better not have to fix complicated merges in this situation because rebase eliminates merges). Then you go like this:

# We're going to create the goal situation in a new branch
git checkout -b fixed-branch
git rebase --onto master@{1} HEAD~4
# If conflicts occur, fix and git rebase --continue etc.
# In case things are okay now, overwrite master with this
git checkout master
git reset --hard fixed-branch
git branch -d fixed-branch
This article was written by Jan Krüger. See history of changes.