Michael Clark
Michael Clark

Reputation: 462

Recover a Git branch that was deleted months ago

I deleted a branch months ago thinking that it was no longer required in my project. It turns out that now, months later, it's actually required again. I don't have it locally unfortunately...

Is there a way I can restore it?

EDIT: I have cloned the repo after deleting the branch, so I believe the reflog can't help me.

I have also tried the "Resurrect" http://repo.or.cz/w/git.git/blob/HEAD:/contrib/git-resurrect.sh which isn't showing me the branch.

EDIT #2 : Those are all good answers but I think I'm screwed. The reflog is of no help to me any more since I've re-cloned, it was a branch sitting out all by itself, it's not on the remote server and nobody else has it locally.

I think I'll just rewrite it...

Upvotes: 1

Views: 504

Answers (3)

Francois Grossin
Francois Grossin

Reputation: 11

Can you try git reflogand find the latest commit hash for the branch that you have deleted ?
Once you have the commit hash, perform git reset --hard <commit>.
This will revert the HEAD back to the latest commit on the branch.
Recreate the branch again and checkout to that new branch git checkout -b <branchname>
Then push the branch, git push origin <branchname>

I found this on the Atlassian Knowledge Base at https://confluence.atlassian.com/stashkb/how-to-restore-a-deleted-branch-744723130.html

I hope this helps

Upvotes: 1

CodeWizard
CodeWizard

Reputation: 142632

You can recover the branch if one of below options occur:

(Specify if any and ill update the answer accordingly)

  • If you have merged the branch to some other branch
  • You have it stored locally on your repo (which mean that no gc was running during this time)
  • You have it on the remote server
  • Someone else has it in his repo
  • You have a clue which file you are looking for and this will allow me to explain how to search the git blobs looking for it)

Mean while take a look here for more ideas: How to move HEAD back to a previous location? (Detached head)

Upvotes: 1

Farhad
Farhad

Reputation: 13006

Yes, you can recover a deleted branch in git.

First, run git reflog and find the SHA1 for the commit at the tip of your deleted branch.

Then just git checkout -b <branchname> <sha> to recreate the branch and its history.

Upvotes: 1

Related Questions