0
0
Gitdevops~15 mins

Recovering deleted branches in Git - Deep Dive

Choose your learning style9 modes available
Overview - Recovering deleted branches
What is it?
Recovering deleted branches in Git means restoring a branch that was removed by mistake or intentionally but needs to be brought back. Git keeps a history of commits, so even if a branch is deleted, its commits often remain accessible. This process involves finding the last commit of the deleted branch and creating a new branch pointing to it.
Why it matters
Branches are where developers work on features or fixes. Accidentally deleting a branch can cause loss of work or disrupt collaboration. Without recovery, lost branches might mean lost code, wasted time, or even project delays. Recovering deleted branches helps avoid these problems and keeps development smooth.
Where it fits
Before learning this, you should understand basic Git concepts like commits, branches, and the command line. After mastering recovery, you can explore advanced Git topics like reflog, stash, and undoing changes safely.
Mental Model
Core Idea
A deleted branch is just a label removed from a commit; the commit still exists until garbage collected, so you can restore the branch by pointing a new label to that commit.
Think of it like...
Imagine a bookmark in a book marking your place. Deleting a branch is like removing the bookmark, but the page is still there. You can put a new bookmark back on that page to find your spot again.
┌───────────────┐
│ Commit History│
│  ●─●─●─●─●    │
└─────┬─────────┘
      │
  Deleted branch label removed
      │
  Commit still exists in history
      │
  Create new branch label pointing here
      ↓
┌───────────────┐
│ Restored branch│
│     ●         │
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Git branches and commits
🤔
Concept: Branches are pointers to commits; commits are snapshots of your project.
In Git, a branch is like a named pointer to a commit. Commits are snapshots of your files at a point in time. When you create a branch, Git just creates a new pointer to a commit. Deleting a branch removes that pointer but not the commits themselves.
Result
You know that branches are just labels pointing to commits, and deleting a branch removes the label but leaves commits intact.
Understanding that branches are pointers helps you realize that deleting a branch doesn't delete the work, just the label.
2
FoundationWhat happens when you delete a branch
🤔
Concept: Deleting a branch removes its pointer but commits remain until cleaned by Git.
When you run 'git branch -d branchname', Git deletes the branch pointer. The commits that branch pointed to still exist in the repository if other branches or references point to them. If no references point to those commits, Git keeps them temporarily before cleaning them up.
Result
Deleting a branch removes the label but commits remain accessible for some time.
Knowing that commits survive branch deletion is key to recovering lost branches.
3
IntermediateUsing git reflog to find deleted branch commits
🤔Before reading on: do you think deleted branch commits disappear immediately or can be found? Commit to your answer.
Concept: Git reflog records changes to branch pointers and HEAD, letting you find commits from deleted branches.
The command 'git reflog' shows a log of where HEAD and branches pointed recently. Even if a branch is deleted, its last commit is recorded here. You can find the commit hash of the deleted branch's tip by scanning reflog entries.
Result
You can identify the commit hash of the deleted branch to restore it.
Understanding reflog as a safety net lets you recover lost commits and branches easily.
4
IntermediateRestoring a deleted branch from commit hash
🤔Before reading on: do you think restoring a branch requires rewriting history or just creating a new pointer? Commit to your answer.
Concept: You can restore a branch by creating a new branch pointing to the commit hash found in reflog.
Once you have the commit hash, run 'git branch branchname ' to create a new branch at that commit. This recreates the branch as if it was never deleted.
Result
The deleted branch is restored and visible again in your branch list.
Knowing that branch restoration is just creating a pointer avoids complex recovery steps.
5
AdvancedRecovering branches deleted long ago
🤔Before reading on: do you think reflog keeps entries forever or only for a limited time? Commit to your answer.
Concept: Reflog entries expire after a time, so recovery depends on how long ago the branch was deleted.
Git keeps reflog entries for 90 days by default. If the branch was deleted longer ago, reflog may not have the commit. You can try 'git fsck --lost-found' to find dangling commits or check remote repositories if pushed.
Result
You may recover older deleted branches using advanced Git commands or backups.
Understanding reflog expiration and dangling commits helps in tough recovery scenarios.
6
ExpertPreventing branch loss with best practices
🤔Before reading on: do you think deleting branches locally affects remote branches automatically? Commit to your answer.
Concept: Using remote backups, protected branches, and careful deletion avoids accidental loss.
Push branches to remote repositories regularly. Use branch protection rules on remotes to prevent deletion. When deleting locally, verify if the branch exists remotely. Use tags or backups for critical branches. Automate reflog cleanup carefully.
Result
Reduced risk of losing important branches and easier recovery if deletion happens.
Knowing prevention techniques is as important as recovery for safe Git workflows.
Under the Hood
Git stores commits as objects identified by hashes. Branches are lightweight pointers to these commits. Deleting a branch removes the pointer but the commit objects remain in the object database until garbage collection. The reflog records movements of HEAD and branch pointers, allowing retrieval of commit hashes even after branch deletion.
Why designed this way?
Git was designed for speed and safety. Keeping commits after branch deletion prevents accidental data loss. Reflog acts as a safety net for human errors. This design balances performance with recoverability, unlike systems that delete data immediately.
┌─────────────┐      ┌─────────────┐
│ Commit A   │◄─────│ Branch master│
├─────────────┤      └─────────────┘
│ Commit B   │◄─────┤ Branch feature│
├─────────────┤      └─────────────┘
│ Commit C   │
└─────────────┘

Branch deletion removes pointer (e.g., feature), commits remain.
Reflog records pointer moves:
HEAD@{0} -> feature@{deleted}

Recovery:
Create new branch pointing to Commit B.
Myth Busters - 4 Common Misconceptions
Quick: Does deleting a branch delete its commits immediately? Commit yes or no.
Common Belief:Deleting a branch deletes all its commits permanently right away.
Tap to reveal reality
Reality:Deleting a branch only removes the pointer; commits remain until garbage collected.
Why it matters:Believing commits are gone causes panic and unnecessary data loss fears.
Quick: Can you recover a deleted branch without reflog? Commit yes or no.
Common Belief:Once a branch is deleted, you cannot recover it without reflog.
Tap to reveal reality
Reality:You can sometimes recover commits using 'git fsck' or from remote backups.
Why it matters:Knowing multiple recovery methods prevents giving up too soon.
Quick: Does deleting a local branch delete the remote branch automatically? Commit yes or no.
Common Belief:Deleting a local branch also deletes the remote branch automatically.
Tap to reveal reality
Reality:Local branch deletion does not affect remote branches unless explicitly deleted.
Why it matters:Misunderstanding this can cause confusion about branch availability.
Quick: Does reflog keep entries forever? Commit yes or no.
Common Belief:Reflog keeps all history forever, so you can always recover deleted branches.
Tap to reveal reality
Reality:Reflog entries expire after a default period (usually 90 days).
Why it matters:Assuming infinite reflog retention can lead to failed recovery attempts.
Expert Zone
1
Reflog is local to your repository; deleted branches pushed to remotes may require remote reflog or server-side recovery.
2
Garbage collection timing affects commit availability; aggressive gc can remove commits sooner than expected.
3
Restoring a branch from reflog does not restore uncommitted changes; stash or other backups are needed for those.
When NOT to use
Recovering deleted branches is not suitable if commits were never pushed or committed; in such cases, recovery requires file system or IDE backups. Also, if commits are garbage collected, recovery is impossible without backups.
Production Patterns
Teams use branch protection rules on remotes to prevent deletion. Automated backups and CI pipelines often push branches regularly. Developers use reflog and recovery commands as part of incident response to fix accidental deletions quickly.
Connections
Version Control Systems
Builds-on
Understanding Git branch recovery deepens knowledge of how version control systems track and manage changes over time.
Data Backup and Recovery
Similar pattern
Recovering deleted branches in Git parallels restoring deleted files in backup systems, highlighting the importance of pointers and snapshots.
Human Memory and Forgetting
Analogy in cognition
Just like reflog helps recover lost commits, human memory has mechanisms to recall forgotten information temporarily before it fades.
Common Pitfalls
#1Trying to recover a deleted branch without checking reflog first.
Wrong approach:git branch branchname # No commit hash specified, creates empty branch
Correct approach:git reflog # Find commit hash git branch branchname
Root cause:Not knowing reflog records recent branch pointers leads to creating branches without history.
#2Assuming deleting a local branch deletes the remote branch.
Wrong approach:git branch -d branchname # Thinks remote branch is deleted too
Correct approach:git branch -d branchname # Deletes local branch only git push origin --delete branchname # Deletes remote branch explicitly
Root cause:Confusing local and remote branch management commands.
#3Waiting too long to recover a deleted branch expecting reflog to keep it forever.
Wrong approach:# After months git reflog # No entry found for deleted branch
Correct approach:# Recover within reflog retention period (default 90 days) git reflog git branch branchname
Root cause:Misunderstanding reflog expiration leads to missed recovery windows.
Key Takeaways
Git branches are just pointers to commits; deleting a branch removes the pointer but not the commits.
Git reflog records recent movements of branch pointers and HEAD, enabling recovery of deleted branches.
Restoring a deleted branch involves creating a new branch pointing to the commit hash found in reflog.
Reflog entries expire after a default time, so timely recovery is important.
Preventing branch loss with remote backups and branch protection is better than relying solely on recovery.