0
0
Gitdevops~5 mins

Recovering deleted branches in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you delete a branch by mistake in Git. This concept shows how to find and restore that deleted branch quickly using Git commands.
When you accidentally delete a branch that had important work.
When you want to restore a branch after cleaning up old branches.
When you realize you need to continue work on a branch you deleted.
When you want to recover a branch after a mistaken git branch -d command.
When you want to find the last commit of a deleted branch to restore it.
Commands
This command shows a log of all recent Git actions including branch deletions. It helps find the commit hash of the deleted branch.
Terminal
git reflog
Expected OutputExpected
abc1234 HEAD@{0}: checkout: moving from feature-branch to main bcd2345 HEAD@{1}: branch: Deleted branch feature-branch (was abc1234) ...
This command recreates the deleted branch named 'feature-branch' at the commit hash abc1234 found from reflog.
Terminal
git branch feature-branch abc1234
Expected OutputExpected
No output (command runs silently)
Switch to the restored branch to continue working on it.
Terminal
git checkout feature-branch
Expected OutputExpected
Switched to branch 'feature-branch'
Key Concept

If you remember nothing else, remember: git reflog helps you find the commit hash to restore a deleted branch.

Common Mistakes
Trying to restore a branch without finding the correct commit hash from reflog.
Git needs the exact commit hash to recreate the branch; without it, the branch cannot be restored.
Always run 'git reflog' first to find the commit hash before recreating the branch.
Using 'git checkout' to switch to a deleted branch before recreating it.
The branch no longer exists, so checkout will fail.
First recreate the branch with 'git branch <name> <commit>' then checkout.
Summary
Use 'git reflog' to find the commit hash of the deleted branch.
Recreate the branch with 'git branch <branch-name> <commit-hash>'.
Switch to the restored branch using 'git checkout <branch-name>'.