Bird
Raised Fist0
Gitdevops~15 mins

Recovering deleted branches in Git - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the primary Git command used to find the commit hash of a recently deleted branch?
easy
A. git reflog
B. git branch -d
C. git reset --hard
D. git merge

Solution

  1. Step 1: Understand the purpose of git reflog

    git reflog records all changes to the HEAD, including deleted branches.
  2. Step 2: Identify the command that shows commit history including deleted refs

    git reflog lets you find the commit hash of the deleted branch.
  3. Final Answer:

    git reflog -> Option A
  4. Quick Check:

    Find deleted branch commit = git reflog [OK]
Hint: Use git reflog to find lost commits fast [OK]
Common Mistakes:
  • Confusing git branch -d as recovery command
  • Using git reset --hard which discards changes
  • Thinking git merge recovers deleted branches
2. Which of the following commands correctly recreates a deleted branch named feature1 from a commit hash abc1234 and switches to it?
easy
A. git checkout -b feature1 abc1234
B. git reset feature1 abc1234
C. git branch feature1 abc1234
D. git checkout abc1234 feature1

Solution

  1. Step 1: Understand the syntax to create a branch at a commit

    The correct syntax is git checkout -b [branch] [commit] to create and switch.
  2. Step 2: Identify the correct command

    git checkout -b feature1 abc1234 creates branch feature1 at commit abc1234.
  3. Final Answer:

    git checkout -b feature1 abc1234 -> Option A
  4. Quick Check:

    Create branch at commit = git checkout -b branch commit [OK]
Hint: Use git checkout -b branch commit to restore branch [OK]
Common Mistakes:
  • Using git checkout commit branch without -b
  • Using git reset which does not create branches
  • Using git branch without switching
3. After deleting a branch bugfix, you run git reflog and see this entry:
abc1234 HEAD@{2}: checkout: moving from bugfix to main

Which command will correctly restore the bugfix branch at that commit?
medium
A. git checkout bugfix
B. git branch -d bugfix abc1234
C. git reset --hard abc1234
D. git checkout -b bugfix abc1234

Solution

  1. Step 1: Identify commit hash from reflog

    The commit hash abc1234 is where bugfix was last checked out.
  2. Step 2: Use command to recreate branch at that commit

    git checkout -b bugfix abc1234 creates and switches to bugfix at that commit.
  3. Final Answer:

    git checkout -b bugfix abc1234 -> Option D
  4. Quick Check:

    Restore branch from commit = git checkout -b branch commit [OK]
Hint: Use reflog commit hash with git checkout -b [OK]
Common Mistakes:
  • Using git branch -d which deletes branches
  • Using git reset --hard which resets HEAD but not branches
  • Trying git checkout bugfix without recreating branch
4. You tried to recover a deleted branch using git checkout -b feature abc123 but got an error: fatal: A branch named 'feature' already exists.
What is the best way to fix this?
medium
A. Use git checkout feature to switch to the existing branch
B. Delete the existing branch first with git branch -D feature then retry
C. Use git branch -b feature abc123 instead
D. Rename the commit hash to a new one

Solution

  1. Step 1: Understand the error

    The error means branch feature already exists locally.
  2. Step 2: Delete existing branch to recreate

    Use git branch -D feature to force delete the existing branch, then recreate it.
  3. Final Answer:

    Delete existing branch with git branch -D feature then retry -> Option B
  4. Quick Check:

    Delete conflicting branch before recreate [OK]
Hint: Delete existing branch with -D before recreating [OK]
Common Mistakes:
  • Trying git branch -b which is invalid syntax
  • Ignoring the existing branch and forcing checkout
  • Renaming commit hash which is not possible
5. You accidentally deleted a branch release and want to recover it. You run git reflog and find multiple commits related to release. Which sequence of commands correctly recovers the branch at the latest commit and deletes the old branch pointer?
hard
A. git checkout -b release
B. git checkout release; git reset --hard
C. git branch -D release; git checkout -b release
D. git branch release

Solution

  1. Step 1: Delete any existing branch pointer named release

    Use git branch -D release to remove old or conflicting branch references.
  2. Step 2: Create a new branch release at the desired commit

    Use git checkout -b release <commit-hash> to recreate and switch to the branch at the correct commit.
  3. Final Answer:

    git branch -D release; git checkout -b release <commit-hash> -> Option C
  4. Quick Check:

    Delete old branch then recreate at commit [OK]
Hint: Delete old branch first, then recreate at commit [OK]
Common Mistakes:
  • Using git checkout release when branch is deleted
  • Using git reset --hard without recreating branch
  • Using git branch release without switching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard