0
0
Gitdevops~5 mins

Recovering from bad rebase in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes when you try to clean up your commit history using rebase, things can go wrong and your code may break or commits get lost. Recovering from a bad rebase helps you go back to a safe state without losing your work.
When you accidentally delete commits during an interactive rebase
When a rebase causes conflicts that you cannot resolve easily
When your branch history looks wrong after rebasing
When you want to undo a rebase and return to the previous branch state
When you realize the rebase introduced bugs and want to start over
Commands
Shows a list of recent changes to HEAD, including before the rebase, so you can find the commit to go back to.
Terminal
git reflog
Expected OutputExpected
abc1234 HEAD@{0}: rebase finished: returning to refs/heads/feature-branch bcd2345 HEAD@{1}: rebase: fix typo cde3456 HEAD@{2}: checkout: moving from main to feature-branch def4567 HEAD@{3}: commit: add new feature ...
Resets your branch to the commit before the bad rebase, discarding all changes after that point to restore the previous state.
Terminal
git reset --hard abc1234
Expected OutputExpected
HEAD is now at abc1234 add new feature
--hard - Resets working directory and index to match the commit
Checks the current state of your branch to confirm you have successfully returned to the previous commit.
Terminal
git status
Expected OutputExpected
On branch feature-branch Your branch is up to date with 'origin/feature-branch'. nothing to commit, working tree clean
Key Concept

If you remember nothing else, remember: git reflog lets you find previous commits to recover from mistakes like bad rebases.

Common Mistakes
Using git reset --hard without checking git reflog first
You might reset to the wrong commit and lose work permanently.
Always run git reflog to find the correct commit hash before resetting.
Trying to fix a bad rebase by making new commits instead of resetting
This complicates history and does not truly undo the bad rebase.
Use git reset --hard to go back to the safe commit, then rebase again carefully.
Summary
Use git reflog to find the commit before the bad rebase.
Use git reset --hard with that commit hash to restore your branch.
Verify your branch state with git status after recovery.