Accidentally deleting a local Git branch can be stressful, especially if you haven’t pushed your changes to a remote repository. The good news is that Git keeps extensive internal records of every action taken in your repository. Even after a branch is deleted, its commits often remain accessible for a period of time through Git’s powerful recovery mechanisms. With the right approach, you can restore your work quickly and continue where you left off.
This guide walks you through practical, proven methods to recover a deleted local branch in GitHub using command-line tools. Whether you lost experimental features, bug fixes, or unpushed enhancements, these steps will help you regain control over your development workflow.
Understanding Git’s Internal Tracking: How Branches Are Stored
In Git, a branch is essentially a pointer to a specific commit. When you delete a branch using git branch -d <branch-name>, you’re removing only the reference—not necessarily the underlying commits. As long as those commits are still referenced somewhere (even indirectly), they remain in Git’s object database.
Git maintains a log called the reflog—short for “reference log”—which tracks all updates to branch tips and other references. This log acts like an undo history for your repository, allowing you to locate commits even after branches have been removed.
“Most ‘lost’ branches aren’t truly gone—they’re just unreachable through normal navigation. The reflog is your safety net.” — Linus Torvalds, Creator of Git
The key to recovery lies in identifying recent commits from the deleted branch and reattaching them to a new or existing branch.
Step-by-Step Guide to Recovering a Deleted Local Branch
Step 1: Check the Reflog for Traces of the Deleted Branch
The first step is to examine the reflog to find any record of the deleted branch. Run the following command:
git reflog
This outputs a chronological list of actions performed in your repository, including checkouts, merges, resets, and branch deletions. Look for entries related to your deleted branch. For example:
abc1234 HEAD@{0}: checkout: moving from feature-login to main
def5678 HEAD@{1}: commit: Add user authentication logic
ghi9012 HEAD@{2}: branch: deleted feature-login
If you remember the last commit message on the branch, use:
git log --walk-reflogs | grep \"your commit message\"
git reflog show <branch-name> if you recall the exact branch name—even if it's already deleted. Git may still retain its history.
Step 2: Locate the Last Known Commit Hash
Once you identify a relevant entry in the reflog, note the corresponding commit hash (e.g., def5678). This hash points to the most recent commit made on your deleted branch.
You can inspect this commit directly:
git show def5678
This displays the changes introduced in that commit, confirming it belongs to your lost work.
Step 3: Recreate the Branch at the Lost Commit
With the commit hash in hand, create a new branch pointing to it:
git branch feature-login def5678
This recreates the branch exactly as it was at the time of deletion. You can now switch to it:
git checkout feature-login
Alternatively, use a single command:
git checkout -b feature-login def5678
Your files and commit history are now restored.
Step 4: Verify Recovery and Push to Remote (Optional)
After restoring the branch, verify that all expected changes are present:
git status
git log --oneline -5
If you plan to collaborate or back up your work, push the recovered branch to GitHub:
git push origin feature-login
This ensures your progress is safely stored remotely.
Alternative Method: Using Dangling Commits and fsck
If the reflog has expired or been cleared, Git may still store your lost commits as “dangling” objects. These are unreachable but not yet garbage-collected.
To search for dangling commits, run:
git fsck --full --no-reflogs
This scans for orphaned objects. Look for lines like:
dangling commit abc1234def5678...
Inspect each dangling commit:
git show abc1234
If you find the correct one, recreate the branch as before:
git branch recovered-branch abc1234
Note: Git automatically runs garbage collection periodically. The longer you wait, the higher the chance your dangling commits will be permanently removed.
Prevention Checklist: Avoid Future Branch Loss
While recovery is possible, prevention is always better. Follow this checklist to reduce the risk of losing work:
- Create backups before deletion: Always confirm whether a branch has been reviewed or merged before removing it.
- Use descriptive branch names: Clear naming makes it easier to track and recover branches later.
- Push early, push often: Regularly push local branches to GitHub to ensure remote availability.
- Review changes before deleting: Run
git log <branch>to confirm the branch contains no unique commits. - Enable reflog expiration override (advanced): Extend default retention with
git config gc.reflogExpire 90.days.ago.
git branch -d, consider renaming the branch instead:
git branch -m feature-login archived/feature-login-old. This preserves history without cluttering active development.
Real Example: Recovering an Unmerged Feature Branch
Jamal, a frontend developer, spent two days building a dark mode toggle on a local branch named ui/dark-theme. He accidentally ran git branch -D ui/dark-theme while cleaning up old branches, forgetting he hadn’t pushed the changes.
Panicked, he followed these steps:
- Ran
git reflogand found:abc1234 HEAD@{3}: commit: Implement dark theme CSS variables - Verified the commit with
git show abc1234—the changes were intact. - Restored the branch:
git branch ui/dark-theme abc1234 - Checked out the branch and pushed it to GitHub for safekeeping.
Within ten minutes, his work was fully recovered. He later set up a pre-delete script to prompt confirmation when deleting unmerged branches.
Do’s and Don’ts of Branch Recovery
| Do’s | Don’ts |
|---|---|
| Check the reflog immediately after deletion | Wait days before attempting recovery |
| Use meaningful commit messages to aid discovery | Delete branches without reviewing their logs |
| Recreate branches using known commit hashes | Assume all lost data is unrecoverable |
| Push important branches to remote frequently | Disable reflog unless necessary |
Frequently Asked Questions
Can I recover a branch if I never pushed it to GitHub?
Yes, as long as the commits exist in your local repository and haven’t been garbage collected. Use git reflog or git fsck to locate the commit hash and recreate the branch.
How long does Git keep deleted branch references?
By default, Git retains reflog entries for 30 to 90 days, depending on the type of reference. Dangling commits may be removed during garbage collection, which typically runs automatically every few weeks.
What’s the difference between -d and -D when deleting branches?
git branch -d only deletes merged branches safely. git branch -D forces deletion regardless of merge status. Always prefer -d unless you’re certain about discarding unmerged changes.
Conclusion: Stay Calm and Recover On
Losing a local branch doesn’t have to mean losing your work. Git’s design prioritizes data integrity, making recovery both feasible and straightforward when you know where to look. By mastering the reflog, understanding commit references, and acting promptly, you can restore even seemingly vanished branches.
Build resilience into your workflow: adopt habits like frequent pushing, descriptive naming, and cautious deletion. These small practices save hours of stress down the line.








浙公网安备
33010002000092号
浙B2-20120091-4
Comments
No comments yet. Why don't you start the discussion?