views:

42

answers:

4

I just deleted the wrong branch with some experimental changes I need with git branch -D branchName.

How do I recover the branch?

+1  A: 

If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution here.

Chetan
How do I find the sha1?
Stefan Kendall
I've updated my answer on how to find the SHA1.
Chetan
A: 

Unless you committed the changes to the remote repository then

git checkout -f branchName
Saul
+3  A: 

You can use git reflog to find the SHA1 of the last commit of the branch. From that point, you can recreate a branch using

git branch branchName <sha1>
bobDevil
A: 

First: back up your entire directory, including the .git directory.

Second: You can use git fsck --lost-found to obtain the ID of the lost commits.

Third: rebase or merge onto the lost commit.

Fourth: Always think twice before using -D or --force with git :)

You could also read this good discussion of how to recover from this kind of error.

EDIT: By the way, don't run git gc (or allow it to run by itself - i.e. don't run git fetch or anything similar) or you may lose your commits for ever.

Cameron Skinner