30

I have deleted my branch by mistake like this:

git branch -D demo

But I want to recover it… I get this after git reflog

541b2f5 HEAD@{23}: checkout: moving from demo to master
06fa6d5 HEAD@{24}: commit (merge): remove ajax call for deleting variables and transfomers
b84b60a HEAD@{25}: checkout: moving from demo1 to demo

I want to create branch with sha 06fa6d5… so I tried this:

git checkout -b demo  06fa6d5

git checkout -b demo  HEAD@{24}

But I didn't get code from that…

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nalini Wanjale
  • 1,717
  • 4
  • 19
  • 24
  • 1
    your commands are correct and should work. Your question lacks details. – Chronial May 28 '13 at 13:46
  • Looks like this was resolved. I really liked this answer for this situation: http://stackoverflow.com/questions/3640764/can-i-recover-branch-after-its-deletion-in-git – CodeFinity Jan 19 '16 at 23:56

2 Answers2

52

Create a list of all dangling or unreachable commits.

git fsck --full --no-reflogs --unreachable --lost-found

Print a list of commit messages for all commits in the lost and found.

ls -1 .git/lost-found/commit/ | xargs -n 1 git log -n 1 --pretty=oneline

Find your missing commit through the process of manual inspection (i.e. reading). Create a new branch with the missing commit as the branch head.

git checkout -b branch-name SHA
vitthal-gaikwad
  • 1,184
  • 11
  • 13
  • 4
    that was amazing. I did this on windows using mysisgit. had to change the process a little bit because the the lost and found directory was not in any sensible place. I took the output of `git fsck...` and checked the SHA for every `commmit` (not blob or tree) by doing a `git log SHA` – David West Dec 13 '13 at 20:40
  • 12
    I have also been to adapt it: `git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\ -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt` – Philippe Mar 10 '14 at 15:11
  • 5
    Philippe's oneline command worked for me in git bash for windows. I just had to add an extra space after -d\ in " cut -d\ -f3 " (cannot show it in comments as the formatting removes duplicate spaces) – BenL Nov 19 '15 at 14:01
  • Nice one @Phillipe! – Diego Palomar Aug 19 '21 at 13:57
1

Having got the potential sha1 for the last tip of branch demo, use gitk sha1 to actually browse the commit's history to check you have the right one.

Philip Oakley
  • 13,333
  • 9
  • 48
  • 71