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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.