Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I recover a branch after its deletion in Git?

If I run git branch -d XYZ, is there a way to recover the branch? Is there a way to go back as if I didn't run the delete branch command?

like image 938
prosseek Avatar asked Sep 04 '10 03:09

prosseek


People also ask

Can a deleted git branch be recovered?

A deleted Git branch can be restored at any time, regardless of when it was deleted. Open your repo on the web and select the Branches view. Search for the exact branch name using the Search all branches box in the upper right. Click the link to Search for exact match in deleted branches.

What happens when a branch is deleted in git?

What Happens If I Delete a Git Branch? When you delete a branch in Git, you don't delete the commits themselves. That's right: The commits are still there, and you might be able to recover them.

How long does git keep deleted branches?

I asked GitHub Support, this was their response (emphasis mine): We use a separate ref namespace for all Pull Requests which we use for various things including restoring the branch. Since we keep those [Pull Request] refs indefinitely, there's no time limit on restoring a branch.


1 Answers

Yes, you should be able to do git reflog --no-abbrev and find the SHA1 for the commit at the tip of your deleted branch, then just git checkout [sha]. And once you're at that commit, you can just git checkout -b [branchname] to recreate the branch from there.


Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.

If you've just deleted the branch you'll see something like this in your terminal Deleted branch <your-branch> (was <sha>). Then just use that <sha> in this one-liner:

git checkout -b <your-branch> <sha> 
like image 98
tfe Avatar answered Oct 13 '22 02:10

tfe