Recover a deleted branch with git reflog

Description: You deleted the branch feature-x with git branch -D and you want it back.

Hint:

  • The reflog keeps the commit. Create a branch from it.

Solution

Terminal output

$ git reflog -3
1e3d759 (HEAD -> main) HEAD@{0}: checkout: moving from feature-x to main
72e9eac HEAD@{1}: commit: Add feature work
1e3d759 (HEAD -> main) HEAD@{2}: checkout: moving from main to feature-x
$ git branch feature-x HEAD@{1}
$ git log –oneline feature-x
72e9eac (feature-x) Add feature work
1e3d759 (HEAD -> main) Add home

How it works

  • HEAD@{1} is the commit where HEAD was before we moved to main, which is the last commit of the deleted branch.
  • The reflog works only on your computer and for some time (90 days by default).

Read Git Reflog.


Learn more about the similar topics:
Tutorials
Git Restore
Git Commit Amend
Git Reset
Git Revert
Git Stash
Git Reflog
Exercises & Assignments
Discard the changes of a file
Undo the last commit but keep the changes
Revert a commit with git revert
Fix the message of the last commit
Stash your changes and bring them back
Recover a deleted branch with git reflog
Interview Questions & Answers
What is git revert?
How to undo last commit using git reset?
What is the difference between git reset and git revert?
What is the difference between soft, mixed and hard reset in Git?
What is git stash and when do you use it?
How do you change the last commit message in Git?
How do you squash commits in Git?