How to Fix Git Recover Deleted Branch with Reflog
In this tutorial, you'll learn about How to Fix Git Recover Deleted Branch with Reflog. We cover key concepts, practical examples, and best practices.
You accidentally deleted a branch with git branch -D and realized you need it back — Git's reflog tracks history of where HEAD pointed, making branch recovery possible.
The Problem
git branch -D feature/my-feature
Deleted branch feature/my-feature (was abc1234).
And you need that branch back.
Step-by-Step Fix
Step 1: Find the lost commit with reflog
git reflog
Expected:
def5678 (HEAD -> main) HEAD@{0}: Branch: renamed refs/heads/feature/my-feature to refs/heads/feature/my-feature
abc1234 HEAD@{1}: commit: Add payment module
The commit abc1234 is where your branch was.
Step 2: Recreate the branch
git branch feature/my-feature abc1234
Step 3: Verify the recovered branch
git log feature/my-feature --oneline -5
Expected:
abc1234 Add payment module
def5678 Fix login bug
...
Step 4: Find dangling commits
If you do not see the commit in reflog:
git fsck --lost-found
Expected:
dangling commit abc1234
dangling blob xyz5678
Recreate the branch from the dangling commit:
git branch recovered-branch abc1234
Step 5: Use git reflog with date filtering
git reflog --date=iso
Find entries before the deletion.
Step 6: Check remote tracking branches
If the branch was pushed:
git checkout --track origin/feature/my-feature
Prevention Tips
- Use
git branch -dinstead of-Dfor safety checks - Push branches to remote regularly
- Set up branch protection on remote
- Use
git reflogbefore garbage collection runs - Create branch aliases to prevent accidental deletion
Common Mistakes with reflog recover
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GIT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro