Git: Undo a rebase with git reflog

Weave and unweave your commits.

This post is an adapted extract from my book Boost Your Git DX, available now.

If you make a mistake whilst rebasing, it might seem hard to undo. But with git reflog, you can find the original commit SHA and revert back to it. Let’s see how with an example.

Imagine you are working on a branch called enhance-herbivore-diet, with four commits:

$ git log --oneline main..
8170d88 (HEAD -> enhance-herbivore-diet) New probiotics
dde58c8 Oregano
43e154b Increase calcium supplement
1f2dc4a Add more leafy greens

You discover someone else has already modified the calcium supplement on main, so you decide to rebase your branch and discard your calcium commit. You run an interactive rebase:

$ git rebase -i main

…and in your editor, you accidentally delete the “Oregano” commit as well:

 pick 1f2dc4a Add more leafy greens
-pick 43e154b Increase calcium supplement
-pick dde58c8 Oregano
 pick 8170d88 New probiotics

You complete the rebase and push:

$ git rebase -i main
Successfully rebased and updated refs/heads/enhance-herbivore-diet.

$ git push
...

But then you realize your mistake. Whoops. How can you retrieve that “oreg-ah-no” commit?

If you happened to have relevant git log output visible in your terminal history, you could grab its SHA from there and use:

$ git cherry-pick dde58c8

But if that is lost, it’s again reflog to the rescue. Pipe the HEAD reflog through grep again to search for the relevant commit:

$ git reflog | grep Oregano
dde58c8 HEAD@{3}: commit: Oregano

There’s the SHA which, again, you can cherry-pick:

$ git cherry-pick dde58c8

Done.

But what if you wanted to do the rebase completely, perhaps because you made several edits? You would need to find the commit before the rebase started.

Check the reflog:

$ git reflog
d9c12c2 (HEAD -> enhance-herbivore-diet) HEAD@{0}: rebase (finish): returning to refs/heads/enhance-herbivore-diet
d9c12c2 (HEAD -> enhance-herbivore-diet) HEAD@{1}: rebase (pick): New probiotics
1f2dc4a HEAD@{2}: rebase (start): checkout main
8170d88 HEAD@{3}: commit: New probiotics
...

The “rebase (start)” message is the first step of the rebase operation. So the previous entry, “commit: New probiotics”, records the commit the branch pointed to before the rebase. Reset the branch back to that SHA:

$ git reset --keep 8170d88

Rebase undone.

Fin

May all your rebases go smoothly,

—Adam


Read my book Boost Your Git DX for many more Git lessons.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: